Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Question Groupwise

Download as pdf or txt
Download as pdf or txt
You are on page 1of 268

OOPS/SOLID

Group_VBNet_WINForm

Group_VBNet_WebForm

Group_ASPNetCore_MVC +C#

Group_React_AspNetCore

Group WPF + MVVVM

Group_VC++_MFC

Group_Java

Group_WPF

SQL
OOP’S Concept Question and Answer
Question 1: - What is OOP’s?
Ans: OOP stands for Object Oriented Programming. It is a programming
methodology that uses Objects to build a system or web applications using
programming languages like C#, Vb.net etc.
Question 2: -Main Pillars of OOP’s?
Ans: There are list of top 6 OOPS concepts that we can implement in all major
programming languages like c#, vb.net etc.
1- Class
2- Object
3- Abstraction
4- Encapsulation
5- Inheritance
6- Polymorphism

Question 3: - What Is Class?


Ans: - A class in OOP is a blueprint that defines the properties and behaviors of
objects.
It encapsulates the common characteristics and allows us to create multiple
instances based on that template.
Here is the syntax and declaration example of Class:

---------------------------------------------------------------------------------------------------------------------------------- -

Question: - What is Method?


Ans: - Method is an object’s behavior.
For example, if you consider “Bike” as a class then its behavior is to get bike
color, engine, mileage etc. Here is the example of Method:
public class Bike
{
//here is some properties of class Bike
public string color;
public string engine;
public int mileage;
//here is some behavior/methods of class Bike
public string GetColor()
{
return "red";
}
public int GetMileage()
{
return 65;
}
}
In the above example GetColor() and GetMileage() are the methods
considered as object’s behavior.
---------------------------------------------------------------------------------------------------------
--
Question 4: - What Is Object?
Ans: - An object is a real-world entity that keeps together property states and
behaviors
Example below: -
Now we have a complete set of class with its properties and methods.
IMP Note: -
So, the question raised in mind is how can we access the class with its
object?
Right?
It is simple to create its object and access Bike class. You can create an object
of class via a single line of code as shown below.

Question 5: - What Is Encapsulation?


Ans: - Binding data and member functions together inside a single unit.
EXAMPLE: -
public class Bike
{
public int mileage = 65;
public string color = "Black";
private string formula = "a*b";
//Its public – so accessible outside class
public int GetMileage()
{
return mileage;
}
//Its public – so accessible outside class
public string GetColor()
{
return color;
}
//Its private – so not accessible outside class
private string GetEngineMakeFormula()
{
return formula;
}
}
public class Program
{
public static void Main (string [] args)
{
Bike objBike = new Bike ();
Console.WriteLine("Bike mileage is: " +
objBike.GetMileage());
//accessible outside "Bike"
Console.WriteLine("Bike color is: " + objBike.GetColor());
//accessible outside "Bike"
//we can't call this method as it is inaccessible outside
"Bike" //objBike.GetEngineMakeFormula();
//commented because we can't access it
Console.Read();
}
}
So, as you can see from above code that we hide GetEngineMakeFormula()
method by using private access modifier because there is no need to give the
make formula to users. So exposed only necessary methods for users to use it
using public access modifier.

Question 5: - What Is Abstraction?


Ans: -Abstraction is the process of hiding certain details and showing only
essential information to the user.

How to Abstract: – By using Access Specifiers


.Net has five access specifiers:-

Public — Accessible outside the class through object reference.


Private — Accessible inside the class only through member functions.
Protected — Just like private but Accessible in derived classes also through
member functions.
Internal — Visible inside the assembly. Accessible through objects.
Protected Internal — Visible inside the assembly through objects and in
derived classes outside the assembly through member functions.
Example: -
public class Bike
{
public int mileage = 65;
public string color = "Black";
private string formula = "a*b";
//Its public – so accessible outside class
public int GetMileage()
{
return mileage;
}
//Its public – so accessible outside class
public string GetColor()
{
return color;
}
//Its private – so not accessible outside class
private string GetEngineMakeFormula()
{
return formula;
}
//Its public – so accessible outside class
public string DisplayMakeFormula()
{
//"GetEngineMakeFormula()" is private but accessible and
limited to this class only
return GetEngineMakeFormula();
}
}

public class Program


{
public static void Main (string [] args)
{
Bike objBike = new Bike ();
Console.WriteLine("Bike mileage is: " + objBike.GetMileage());

//accessible outside "Bike"


Console.WriteLine("Bike color is: " + objBike.GetColor());
//accessible outside "Bike"
//we can't call this method as it is inaccessible outside
"Bike"
//objBike.GetEngineMakeFormula();
//commented because we can't access it
Console.WriteLine("Bike color is: " + objBike.DisplayMakeFormula());

//accessible outside
Console.Read();
}
}

Note: Abstraction and Encapsulation are related features


in object-oriented programming. Abstraction allows making
relevant information visible and Encapsulation enables a
programmer to implement the desired level of abstraction.
That means hidden part of class acts like Encapsulation
and exposed part of class acts like Abstraction.

Question: Information/Data Hiding in C#?


Ans: Information Hiding concept restricts direct exposure
of the data. Data is accessed indirectly using safe
mechanisms and methods in the case of programming objects.
Follow the example given in Abstraction.

Question 6: What Is Inheritance?


Ans:- Child Class Inherit Method and Properties of Base Class or
The class being inherited from is called the base class or parent class, and the
class that inherits is called the derived class or child class.
Example:
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk () // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}

class Car: Vehicle // derived class (child)


{
public string modelName = "Mustang"; // Car field
}

class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar
object
myCar.honk();

// Display the value of the brand field (from the Vehicle class)
and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}

Question 7: What Is Polymorphism?


Ans: - Polymorphism means "many forms", and it occurs when we have
many classes that are related to each other by inheritance.
Example: -
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create an Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

: -There are two types of Polymorphism:


1- Compile Time Polymorphism/ Early Binding
i)- Method Overloading
ii)- Operator Overloading
2- Run Time Polymorphism / Late Binding
i)- Virtual/Overriding Method
Compile Time Polymorphism/ Early Binding: - The Mechanism if linking a
function with an object during compile time is called Early Binding. It is Also
called Static Polymorphism
It is also a static Binding.
i) -Method Overloading: - You can have multiple
definitions for the same function name in the scope
(Class).
In short “Same Methods with Different Signature
(Parameters)”
Example: -

using System;
class GFG {

// adding two integer values.


public int Add (int a, int b)
{
int sum = a + b;
return sum;
}

// adding three integer values.


public int Add (int a, int b, int c)
{
int sum = a + b + c;
return sum;
}

// Main Method
public static void Main (String [] args)
{

// Creating Object
GFG ob = new GFG ();

int sum1 = ob.Add (1, 2);


Console.WriteLine("sum of the two "
+ "integer value: " + sum1);
int sum2 = ob.Add (1, 2, 3);
Console.WriteLine("sum of the three "
+ "integer value: " + sum2);
}
}

ii) - Operator Overloading: - the ability to provide the operators


with a special meaning for a data type, this ability is known as operator
overloading.
An operator can be overloaded by defining a function to it. The function of the
operator is declared by using the operator keyword.

Example: -
using System;
namespace Calculator {

class Calculator {

public int number1, number2;


public Calculator(int num1 , int num2)
{
number1 = num1;
number2 = num2;
}

// Function to perform operation


// By changing sign of integers
public static Calculator operator -(Calculator c1)
{
c1.number1 = -c1.number1;
c1.number2 = -c1.number2;
return c1;
}

// Function to print the numbers


public void Print ()
{
Console.WriteLine ("Number1 = " + number1);
Console.WriteLine ("Number2 = " + number2);
}
}

class EntryPoint
{

// Driver Code
static void Main (String []args)
{

// using overloaded - operator


// with the class object
Calculator calc = new Calculator (15, -25);

calc = -calc;

// To display the result


calc.Print();
}
}

What is an EXE and a DLL?


EXE and DLLs are assembly executable modules.
EXE is an executable file that runs the application for which it is designed, An EXE is
produced when we build an application. Therefore the assemblies are loaded directly when
we run an EXE. However, an EXE cannot be shared with the other applications.
Dynamic Link Library (DLL) is a library that consists of code that needs to be hidden. The
code is encapsulated inside this library. An application can consist of many DLLs which can
be shared with the other programs and applications.

SOLID

SOLID is a set of guidelines or rules that help software developers write clean, maintainable,
and flexible code.
The following five concepts make up our SOLID principles/SOLID is an acronym that stands
for:

Single Responsibility
Open/Closed
Liskov Substitution
Interface Segregation
Dependency Inversion

• Single Responsibility Principle (SRP): This principle says that each class or object
should have only one job or responsibility. It's like a person doing only one task really
well. For example, if you have a toy robot, it should only do things related to being a
robot, like moving and making sounds, but not things like cooking or cleaning.

• Open/Closed Principle (OCP): This principle means that once a class is written and
working, it should be closed for modification, but open for extension. It's like a toy car
that you can change and add new parts to, but you don't have to change the whole
car to do it. You can add new wheels or change the colour without modifying the
entire car.

• Liskov Substitution Principle (LSP): This principle states that objects of a


superclass should be able to be replaced by objects of its subclasses without
breaking the program. It's like having different kinds of toys, such as a car and a
plane, that you can play with in the same way. Even though they are different, you
can still have fun with both of them.
• Interface Segregation Principle (ISP): This principle suggests that you should have
smaller and more specific interfaces, rather than having one big interface that does
too much. It's like having different buttons on a toy with each button doing only one
thing. You don't need a single big button that does everything.

• Dependency Inversion Principle (DIP): This principle states that classes should
depend on abstractions (more general things) rather than concrete implementations
(specific things). It's like playing with building blocks. You don't need to know exactly
how each block is made; you just need to know how they fit together to build
something cool.

Q1) What are the advantages of following SOLID principles in software


development?

=> Following SOLID principles in software development has several advantages,


including:
• Maintainability: Code that adheres to SOLID principles is easier to maintain
and modify over time, as it is structured in a clear and organised way.
• Flexibility: SOLID code is also more flexible, as changes to one part of the
system are less likely to have unintended consequences in other parts of the
codebase.
• Testability: SOLID code is easier to test, as it is designed with the principles
of separation of concerns and dependency inversion in mind.
Q2) How do you ensure Single Responsibility Principle (SRP) in your code?

=> To ensure Single Responsibility Principle (SRP) in my code, I follow these


guidelines:
1. Each class should have only one responsibility.
2. The class should have only one reason to change.
3. The class should do one thing, and do it well.
Q3) How do you implement Open-Closed Principle (OCP) in your code?

=> To implement the Open-Closed Principle (OCP) in my code, I follow these


guidelines:
4. Design classes to be easily extended.
5. Use abstractions such as abstract classes or interfaces to define extension
points.
6. Avoid making changes to existing code when adding new functionality.
Q4) How do you ensure the Liskov Substitution Principle (LSP) in your code?

=> To ensure Liskov Substitution Principle (LSP) in my code, I follow these


guidelines:
7. Ensure that subtypes can be substituted for their base types without affecting
the correctness of the program.
8. Subtypes should not change the preconditions or postconditions of the
methods of their base types.
9. Subtypes should not introduce new exceptions that are not part of the
exception hierarchy of their base types.
Q5) How do you apply Interface Segregation Principle (ISP) in your code?
=> To apply Interface Segregation Principle (ISP) in my code, I follow these
guidelines:
10. Define small, focused interfaces that are specific to the needs of the clients
that use them.
11. Avoid creating large, monolithic interfaces that force clients to implement
methods they don't need.
12. Prefer multiple, specialised interfaces over a single, general-purpose
interface.
Q6) How do you apply the Dependency Inversion Principle (DIP) in your code?

=> To apply Dependency Inversion Principle (DIP) in my code, I follow these


guidelines:
13. Define high-level modules that depend on abstractions, not on concrete
implementations.
14. Define low-level modules that provide concrete implementations for the
abstractions used by high-level modules.
15. Use dependency injection to provide the concrete implementations to the
high-level modules.
Q7) How do you deal with tight coupling in your code?
=> To deal with tight coupling in code, one approach is to use design patterns and
principles such as Dependency Inversion Principle (DIP) and Dependency Injection.
By using DIP, high-level modules depend on abstractions instead of concrete
implementations, reducing coupling. In addition, Dependency Injection allows
dependencies to be injected into a class instead of being tightly coupled within the
class itself. Here's an example of how Dependency Injection can be used to reduce
tight coupling in a class:
Q8) What are the benefits of loose coupling in software development?

=> Loose coupling in software development has several benefits, including:


16. Flexibility: loosely coupled code can be easily modified or extended without
affecting other parts of the system, making it easier to adapt to changing
requirements.
17. Testability: loosely coupled code is easier to test because it can be tested in
isolation, reducing the risk of bugs and improving the overall quality of the
code.
18. Maintainability: loosely coupled code is easier to maintain because changes
can be made to a specific module without affecting the rest of the system.
Q9) How would you identify if a codebase violates the Single Responsibility
Principle (SRP)?

=> To identify if a codebase violates the Single Responsibility Principle (SRP), we


can look for classes or methods that have more than one reason to change. If a
class or method is responsible for more than one thing, it violates the SRP.
Q10) How would you ensure adherence to the Liskov Substitution Principle
(LSP) when designing a new class hierarchy?

=> To ensure adherence to the Liskov Substitution Principle (LSP) when designing a
new class hierarchy, we need to ensure that any subclass can be used in place of its
parent class without affecting the correctness of the program. Here are some
guidelines:
• Each subclass should implement all the methods of its parent class.
• The preconditions of the overridden methods in the subclass should not be
stronger than those in the parent class.
• The postconditions of the overridden methods in the subclass should not be
weaker than those in the parent class.
• The invariants of the parent class should be preserved in the subclass.
Q11) How would you refactor a codebase to adhere to the Interface
Segregation Principle (ISP)?

=> To adhere to the Interface Segregation Principle (ISP), we should break down
large interfaces into smaller and more specialised ones so that clients only need to
depend on the interfaces that they actually use. Here are some steps we can take to
refactor a codebase to adhere to ISP:
19. Identify interfaces that are too large or that have methods that are not being
used by their clients.
20. Break down those interfaces into smaller and more specialised ones, based
on the needs of the clients that use them.
21. Make sure that clients only depend on the interfaces that they actually use.
Q12) How would you design a dependency injection container to adhere to the
Dependency Inversion Principle (DIP)?
=> A dependency injection container is a tool used to implement the Dependency
Inversion Principle (DIP) by providing a mechanism for loosely coupling objects and
their dependencies. To design a dependency injection container that adheres to the
DIP, you can define interfaces for your dependencies and then use those interfaces
to inject concrete implementations.

WPF Question

1. What is WPF?

WPF (Windows Presentation Foundation) is a graphical subsystem and a user interface


framework provided by Microsoft as part of the .NET framework. It is designed to develop
visually great and interactive applications for Windows desktop. WPF offers a wide range of
features and capabilities that enable developers to create modern and good-looking user
interfaces.
WPF provides a great platform for building desktop applications with modern user interfaces.
Its combination of XAML, powerful graphics capabilities, data binding, and rich controls
make it a popular choice for developing Windows desktop applications.

Here are some key aspects of WPF:

1. XAML (eXtensible Application Markup Language): WPF uses XAML as its markup
language. XAML allows developers to define the user interface and the visual elements of an
application in a declarative manner, separate from the application logic. It provides a clean
separation between the UI and the code-behind.

2. Controls and Styles: WPF provides controls that can be easily customized and styled to
achieve a consistent and visually appealing look. Controls such as buttons, textboxes, list
boxes, menus, and more are available, and developers can define their own styles and
templates as per their need.

3. Data Binding: WPF provides data binding capabilities, allowing developers to establish a
connection between the UI elements and the data sources. It supports different types of data
binding modes (one-way, two-way, etc.) and facilitates automatic synchronization between
the UI and the data.

4. Layout Management: WPF includes flexible and powerful layout management


mechanisms, enabling developers to arrange and position controls dynamically. Layout
panels like StackPanel, Grid, and DockPanel, along with features like automatic resizing and
alignment, help in creating responsive and adaptive UI layouts.

2. What is MVVM pattern in WPF?

The MVVM (Model-View-ViewModel) pattern is a software architectural pattern commonly


used in WPF (Windows Presentation Foundation) applications. It provides a structured way
to separate the concerns of data, UI presentation, and user interactions. Let's understand
the MVVM pattern:

1. Model:
- The Model represents the data and business logic of your application.
- It could be classes that define the data structure, retrieve data from a database, or
perform calculations.
- The Model is independent of the UI and does not know anything about how the data will
be presented.

2. View:
- The View represents the user interface, including the visual elements and controls that
users interact with.
- It is responsible for displaying the data from the ViewModel and capturing user input.
- In WPF, the View is typically defined using XAML, which describes the structure and
appearance of the UI elements.

3. ViewModel:
- The ViewModel acts as a bridge between the Model and the View.
- It provides the data and behaviors required by the View, exposing properties and
commands.
- The ViewModel transforms the data from the Model into a format that the View can easily
bind to and display.
- It also handles user interactions and performs actions by invoking commands in the
Model.

4. Data Binding:
- Data binding is a key component of the MVVM pattern.
- It allows you to establish a connection between the properties in the ViewModel and the
UI elements in the View.
- Through data binding, changes in the ViewModel are automatically reflected in the View,
and user input is captured and propagated to the ViewModel.
5. Separation of Concerns:
- The MVVM pattern promotes the separation of concerns, allowing different team
members (such as designers and developers) to work on their specific areas.
- The Model focuses on data and business logic, the View on the visual representation,
and the ViewModel on providing data and behavior to the View.

The MVVM pattern helps improve the maintainability, testability, and reusability of WPF
applications. It enables a clear separation between the UI and business logic, making it
easier to modify and enhance the application without affecting other parts. The ViewModel
acts as a mediator, allowing the View to remain independent of the Model and facilitating
efficient development and testing workflows.

3. How does data binding work in WPF?

Data binding in WPF is a way to connect data from a source (such as variables, properties,
or collections) to the user interface (UI) elements of your application. It ensures that changes
in the data are automatically reflected in the UI, and vice versa. Let's understand how data
binding works in simple language:

Imagine you have a textbox in your application, and you want its content to be synchronized
with a variable or property. Data binding allows you to establish a connection between the
textbox and the data source. Here's how it works:

1. Establishing the Binding:


- You specify the data source and the property you want to bind to in the XAML markup.
- For example, you can bind the Text property of a textbox to a property called "Name" in a
ViewModel.
- This tells WPF that you want the textbox to display the value of the "Name" property.
2. Data Source and DataContext:
- The data source can be an object, a property of an object, or a collection.
- In WPF, you set the data source by assigning an instance of your ViewModel or any
other object to the DataContext property of a control or container.
- The DataContext serves as the source of data for all the bindings within that control or its
child elements.

3. Update and Two-Way Binding:


- By default, data binding in WPF is two-way, meaning changes in the UI are reflected
back to the data source.
- When the user modifies the textbox content, the bound property in the data source is
automatically updated.
- Likewise, if the property in the data source changes, the textbox content is automatically
updated.

4. Change Notification:
- For two-way binding to work properly, the data source (such as the ViewModel) should
implement the INotifyPropertyChanged interface.
- This interface provides a way for the data source to notify the UI about changes in the
bound properties.
- When a property changes, the data source raises an event, notifying the UI to update the
bound elements.

5. Value Converters:
- Sometimes, you may need to convert the data from the source to a different format or
vice versa.
- WPF provides value converters that allow you to perform such conversions.
- For example, you can convert a DateTime object to a formatted string for display in a
textbox.

By using data binding in WPF, you eliminate the need to manually synchronize data between
the UI and your data source. Any changes made in the UI or the data source are
automatically reflected in the other, resulting in a responsive and dynamically updated user
interface. Data binding simplifies UI development, promotes separation of concerns, and
ensures consistency between data and UI elements.

4. What are the different types of panels available in WPF for layout management?

In WPF, panels are used for organizing and arranging controls in a specific layout. Think of
panels as containers that hold controls and determine how they are positioned and displayed
on the screen. Here are a few types of panels available in WPF, explained in simple
language:

1. StackPanel:
- Imagine a stack of items, one on top of another or side by side.
- A StackPanel arranges controls either vertically or horizontally, depending on its
orientation.
- Controls added to a StackPanel are placed one after another in the stacking direction.

2. Grid:
- Picture a table with rows and columns.
- A Grid allows you to divide the available space into rows and columns to position
controls.
- Controls can be placed in specific cells of the grid, allowing for precise layout and
alignment.

3. DockPanel:
- Think of a dock where you can anchor objects to different edges.
- A DockPanel allows controls to be "docked" to the top, bottom, left, or right edges.
- Docked controls occupy the full width or height along the specified edge, while remaining
space is filled by other controls.

4. WrapPanel:
- Imagine a horizontal or vertical strip that wraps to the next line when space runs out.
- A WrapPanel arranges controls in a flow-like manner, wrapping to the next line when
necessary.
- Controls are placed one after another, and when the available space is filled, they wrap
to the next line.

5. Canvas:
- Think of a blank canvas where you can freely position controls at specific coordinates.
- A Canvas allows controls to be positioned at precise X and Y coordinates within the
panel.
- Controls are placed wherever you specify, giving you complete control over their
placement.

These panel types offer different ways to manage the layout and positioning of controls in
your WPF application. StackPanel allows for simple stacking, Grid provides a structured
table-like layout, DockPanel enables anchoring controls to edges, WrapPanel allows for
flexible wrapping, and Canvas offers absolute positioning. By choosing the appropriate panel
type, you can achieve the desired layout and arrangement of controls in your user interface.

4. What is the role of resource dictionaries in WPF.

In WPF, resource dictionaries play a significant role in managing and organizing reusable
resources such as styles, templates, brushes, data templates, and more. A resource
dictionary is a XAML file that contains a collection of resources that can be shared and
accessed by multiple elements in an application.

5. What is commands in WPF?

Commands in WPF provide a way to encapsulate and handle user actions or application
functionality in a decoupled and reusable manner. They enable a separation between the UI
controls that trigger actions and the logic that performs those actions. The purpose of
commands is to provide a consistent and extensible approach to handle user interactions.

6. How can you apply styles and templates to WPF controls?


Applying styles and templates to WPF controls allows you to change their appearance and
behavior to create a customized and consistent user interface. Let's understand how to do
this in simple language:

1. Styles:
- Styles are like predefined sets of properties that you can apply to one or more controls.
- Think of styles as a way to give controls a specific look and feel.
- For example, you can create a style that sets the background color, font size, and other
properties of buttons.
- Once you define a style, you can easily apply it to multiple buttons or other controls to
make them all look the same.
- It's like applying a predefined design to multiple elements in one go.

2. Templates:
- Templates allow you to completely change the structure and appearance of a control.
- Think of a template as a blueprint or skeleton for a control.
- With a template, you can redefine how a control looks, including its layout, visual
elements, and behavior.
- For example, you can create a template for a ListBox that changes the way items are
displayed or adds additional visual elements.
- Templates let you go beyond changing properties and enable you to create a unique and
custom design for controls.

To use styles and templates:

1. Define the Style or Template:


- In XAML, you create a Style or ControlTemplate element and specify the properties or
structure you want to change.
- For styles, you typically define it as a resource in a resource dictionary, either in the
XAML file or in a separate resource dictionary file.
- For templates, you usually define it inline within the control that you want to customize, or
in a resource dictionary.

2. Apply the Style or Template:


- To apply a style, you set the Style property of a control to the defined style.
- To apply a template, you set the Template property of a control to the defined template.
- You can apply the style or template directly in the XAML markup of the control or use
resources to reference them.

By applying styles and templates, you can easily change the appearance and behavior of
controls in your WPF application. Styles help you maintain a consistent design across
multiple controls, while templates allow you to create unique and custom designs for
controls. It's like giving controls a new look and feel or changing their structure to suit your
specific design requirements.

7- Explain the concept of routed events in WPF.

In WPF, routed events provide a way to handle and respond to user interactions or other
events that occur in the UI. Routed events follow a hierarchical route, allowing multiple
elements to participate in the event handling process. Here's a simplified explanation of the
concept of routed events in WPF:

Imagine you have a button inside a grid, which is inside a window. When you click the
button, a "Click" event is raised. Routed events enable this "Click" event to travel through a
route, involving multiple elements in the UI hierarchy.

Tunnelling Phase:

The event starts from the top-most element (the window) and travels down the visual tree
towards the target element (the button).
During the tunneling phase, the event is known as a "tunneling event" and uses a predefined
tunneling route.
Parent elements can choose to handle the event at this stage, even before reaching the
target element.
Target Phase:

Once the event reaches the target element (the button), it enters the target phase.
The event is raised and handled by the target element itself.
This phase is also known as the "direct event" phase.
Bubbling Phase:

After the target phase, the event starts to travel back up the visual tree, from the target
element towards the top-most element.
During the bubbling phase, the event is known as a "bubbling event" and uses a predefined
bubbling route.
Parent elements can handle the event at this stage, reacting to it as it bubbles up.
The key idea behind routed events is that multiple elements can handle the same event
along the event route, allowing for flexible event handling and interaction. Elements can
choose to handle events at different phases, enabling customization and intervention at
various levels of the UI hierarchy.

8- What is the purpose of converters in WPF data binding? Give an example

Converters in WPF data binding are used to convert data from one format to another during
the binding process. They allow you to modify the data before it is displayed in the UI or
before it is passed back to the data source.
Imagine you have a numeric value in your data source that you want to display as a
formatted string in a TextBlock. However, the numeric value itself cannot be directly
displayed as desired. Here's where converters come into play:

1. Purpose of Converters:
- Converters provide a way to customize the conversion logic between the data source and
the UI elements.
- They allow you to transform the data to a different format, such as changing the data
type, applying formatting, or performing calculations.
- Converters can be useful in scenarios where the data needs to be modified before being
displayed or when the input provided by the user needs to be transformed before being
stored.

2. Implementing a Converter:
- To create a converter, you need to implement the IValueConverter interface provided by
WPF.
- The IValueConverter interface has two methods: Convert and ConvertBack.
- The Convert method is called when data flows from the data source to the UI, converting
the source value to the desired format.
- The ConvertBack method is called when data flows from the UI back to the data source,
converting the UI value to the source format.
- You can customize the logic within these methods to perform the necessary conversions.

3. Example - Formatting a Numeric Value:


- Let's say you have a numeric value, such as a double, that you want to display with two
decimal places.
- You can create a converter that takes the numeric value and returns a formatted string.
- Here's an example of a converter that performs this conversion:

```csharp
using System;
using System.Globalization;
using System.Windows.Data;

public class NumericToStringConverter : IValueConverter


{
public object Convert(object value, Type targetType, object parameter, CultureInfo
culture)
{
if (value is double numericValue)
{
return numericValue.ToString("N2"); // Format as a number with 2 decimal places
}
return value.ToString();
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo


culture)
{
throw new NotSupportedException(); // Not used in this example (one-way
conversion)
}
}
```

4. Using the Converter in XAML:


- In your XAML markup, you can apply the converter to the data binding using the
Converter property.
- For example, if you have a TextBlock bound to a numeric value, you can apply the
converter like this:

```xaml
<Window.Resources>
<local:NumericToStringConverter x:Key="NumericConverter" />
</Window.Resources>

<TextBlock Text="{Binding NumericValue, Converter={StaticResource


NumericConverter}}" />
```
- In this example, the NumericToStringConverter is applied to the Text property of the
TextBlock.
- When the data is retrieved from the NumericValue property, it is passed through the
converter before being displayed in the TextBlock.

By using converters in WPF data binding, you have the flexibility to modify the data format,
apply custom logic, or perform calculations before it is displayed or stored. Converters help
customize the data conversion process and allow you to present data in a more suitable and
meaningful way in the UI.

9- How can you create custom controls in WPF? Explain the steps involved.

Creating custom controls in WPF allows you to build reusable UI components tailored to
your specific needs. Here are the steps involved in creating custom controls in simple
language:

1. Define the Control:


- Start by creating a new class that inherits from an existing WPF control, such as Button,
TextBox, or UserControl.
- This class will serve as the code-behind for your custom control, providing the logic and
behavior.
- Define any additional properties, events, or methods that are specific to your custom
control.

2. Create the Control Template:


- The control template defines the visual appearance and structure of your custom control.
- You can define the template in XAML by creating a new Style or ControlTemplate
element.
- Design the visual layout of the control, including the position and styling of its various
elements.
- Use XAML elements such as Grid, StackPanel, or Border to structure and arrange the
visual elements.

3. Apply the Control Template:


- In the constructor or initialization code of your custom control, apply the control template
to the control.
- Use the `DefaultStyleKey` property to set the key of the control template to be applied.
- This associates the control with its defined visual appearance and behavior.

4. Register Dependency Properties:


- If your custom control needs customizable properties, you can define them as
dependency properties.
- Dependency properties enable data binding, property value inheritance, and property
change notifications.
- Register the dependency properties using the `DependencyProperty.Register()` method.
- Specify the property name, its data type, the owner type (your custom control), and any
additional metadata.

5. Implement Control Logic:


- Implement the logic and behavior specific to your custom control.
- Handle events, process user input, update properties, and respond to changes in the
control's state.
- You can override existing methods or implement new methods as needed.

6. Test and Use the Custom Control:


- Build and run your application to test your custom control.
- Use the custom control in your XAML markup by referencing its namespace and
including an instance of the control.
- Set properties, handle events, and interact with the custom control as you would with any
other WPF control.
By following these steps, you can create a custom control in WPF that encapsulates specific
functionality, behavior, and visual appearance. Custom controls allow you to create reusable
components that can be easily used across different applications, promoting code reusability
and maintainability.

10- What are dependency properties in WPF? How do they differ from regular
properties?

In WPF, dependency properties are a specialized type of property that provide several
additional capabilities compared to regular properties. They are a fundamental concept in
WPF and offer enhanced features for data binding, property value inheritance, and change
notifications. Let's understand dependency properties and how they differ from regular
properties:

1. Definition of Dependency Properties:


- Dependency properties are properties that are registered with the WPF dependency
property system.
- They are defined as special static fields within a class, typically the code-behind of a
WPF control or a custom class.
- Dependency properties are typically registered using the
`DependencyProperty.Register()` method, specifying the property name, type, owner type,
and optional metadata.

2. Value Resolution and Inheritance:


- Dependency properties provide a mechanism for resolving property values in a more
advanced and flexible way.
- They support value inheritance, which means that a dependency property value can be
inherited from a parent element to its child elements.
- When a dependency property is not explicitly set on an element, the value is resolved
based on the element's parent hierarchy.

3. Data Binding:
- Dependency properties are designed to work seamlessly with data binding in WPF.
- They support two-way data binding, allowing data to flow between the property value and
the data source.
- By defining a dependency property, you can easily bind it to other elements, properties,
or data sources in your application.

4. Change Notification:
- Dependency properties provide a built-in change notification mechanism.
- When a dependency property value changes, the property system automatically notifies
any registered listeners, such as data binding expressions or event handlers.
- This enables UI updates, recalculations, or any other action that needs to be performed
when a property changes.

5. Property Metadata:
- Dependency properties support metadata, which allows you to specify additional
information about the property.
- Metadata can include default values, property change callbacks, validation rules, or other
custom behavior.
- Metadata helps define the behavior and characteristics of the dependency property.

6. XAML and Style Setters:


- Dependency properties can be easily set and manipulated in XAML markup.
- They can be assigned values directly in XAML or through style setters.
- The flexibility of dependency properties in XAML allows for dynamic changes to the
property values, enabling more expressive and customizable UI designs.

In summary, dependency properties in WPF offer advanced features such as value


resolution, inheritance, data binding, change notifications, and metadata. They provide a
powerful mechanism for creating dynamic and interactive user interfaces. Compared to
regular properties, dependency properties offer greater flexibility, enhanced data binding
capabilities, and the ability to inherit and propagate values through the visual tree.

Q1. What is WPF?


Answer- WPF stands for Windows Presentation Foundation.
It is a platform provided by Microsoft as part of the .NET framework for building visually
appealing and interactive user interfaces for Windows desktop applications.
WPF offers a rich set of tools, controls, and features that enable developers to create
modern, engaging, and highly customizable applications .

Q2. What are the types of documents supported by WPF?


Answer-Two types of the documents supported by Windows Presentation Foundation
(WPF) are the Flow document and Fixed document.

1. Flow documents-Flow format document alters the content to fit the screen size.
They are designed to optimize viewing and readability.

EXAMPLE
A Web page is a simple example of a flow document where the page content is dynamically
formatted to fit in the current window.
2.Fixed documents-document present content irrespective of the screen size.
They are intended for applications that require a precise "what you see is what you
get"

Example: Flow documents optimize the viewing and reading experience for the user,
based on the runtime environment.

Q3. What is the namespace required for working with 3D .

Answer-The namespace required for working in 3D is System.Windows.Media.Medi3D.

A namespace is a declarative Package that contains/Provide


scope to the identifiers (the names of types, functions, variables, etc).

Q4. Is it right to say that WPF has replaced DirectX?


Answer-No, WPF can never replace DirectX.
WPF cannot be used to create games with stunning graphics.

WPF is meant to be a replacement for windows form, not DirectX.

Microsoft DirectX is a collection of application programming interfaces for handling tasks


related to multimedia, especially game programming and video, on Microsoft platforms.

Q5. What are dependency properties?


Answer-Properties that belong to a specific class but can be used for another are called the
dependency properties.

A dependency property can reference a value through data binding. Data binding works
through a specific markup extension syntax in XAML, or the Binding object in code.
Q6. How can the size of StatusBar be increased proportionally?
Answer-By overruling the ItemsPanel attribute of StatusBar with a grid. The grid’s columns
can be appropriately configured to get the desired result.

A status bar is a graphical control element which poses an information area typically found
at the window's bottom. It can be divided into sections to group information.

Q7. What are Freezable objects in WPF?


Answer-An object, which has its state locked down, so that it becomes unchangeable, is
known as a freezable object. Such objects perform better. It is also safer if they are
required to be shared between threads.

A thread is a single sequential flow of control within a program.

Q8. Why should WPF be preferred over Adobe Flash?


Answer-WPF is a more recent technology and thus has the latest development tools.
It supports a broader range of programming languages for Logic (C#,VB.net, F#)
and has a robust control reuse.
Adobe Flash Player is computer software for viewing multimedia contents, executing rich
Internet applications, and streaming audio and video content created on the Adobe Flash
platform.

Q9. How is Silverlight different from the WPF browser application?


Answer-One of the major differences is that .NET framework is required for running WPF
browser applications on the client machine
But Silverlight runs using only the plug-in. Another point of difference is that applications
made in WPF depend on the OS as .NET Framework only runs on Windows. On the other
hand, the Silverlight plug-in can be installed on those OSs also, which are not Windows.

Microsoft Silverlight is a discontinued application framework designed for writing and


running rich internet applications, similar to Adobe's runtime, Adobe Flash.

Q10. Name the methods present in the DependencyObject.


Answer-It has three objects, namely:

1. SetValue-This function allows you to dynamically set the value of a registered field and
have the options to validate and update the form state.

2.ClearValue- Clear the value of an input or textarea element. Make sure you can interact
with the element before using this command.

3.GetValue-When overridden in a derived class, returns the property value of a specified


object that has the specified binding, index, and culture-specific information.

The DependencyObject class enables Windows Presentation Foundation (WPF) property


system services on its many derived classes.
Q11. Write about PRISM.
Answer-PRISM is a framework for creating complex applications for WPFor Windows
Phone.

PRISM utilizes MVVM, IC, Command Patterns, DI and Separation of Concerns to get loose
coupling.
In computing and systems design, a loosely coupled system is one in which components
are weakly associated with each other, and thus changes in one component least affect
existence or performance of another component

Q12. Is it possible to use Windows Forms in a WPF application?


Answer-Yes, Windows form can be used in WPF. Windows form can appear as a WPF pop.

The controls of this Window form can be placed besides WPF controls in a WPF page by
utilizing the functions of the WindowsFormsHost control that comes preinstalled.

Windows Forms is a free and open-source graphical class library included as a part of
Microsoft .NET, .NET Framework or Mono, providing a platform to write client applications
for desktop, laptop, and tablet PCs.

Q13. Describe CustomControl briefly.


Answer-CustomControl widens the functions of existing controls. It consists of a default
style in Themes/Generic.xaml and a code file. It is the best way to make a control library and
can also be styled or templated
.Use the control library in Audit Manager to access and manage the controls used in
your assessments and frameworks.

Q14. Name the common assemblies used in WPF?


Answer-
There are 3 type of common assemblies used-

a) WindowsBase.dll:- This is the core type constituting the infrastructure of WPF API.

b)PresentationCore.dll:- It defines numerous types constituting the foundation of WPF


GUI layer.
c)PresentationFoundation.dll:- It defines WPF control types, animation & multimedia
support, data-binding support and other WPF services.

Q15. Define Path animations in WPF


Answer-Path animation is a type of animation in which the animated object follows a path
set by the Path geometry.

Animation is a method by which still figures are manipulated so that they appear to be
moving images.

Q16. Can WPF applications be made without XAML?


Answer-Yes, WPF applications can be created without XAML as using code_behind C#
code to create window design and remove “InitializeComponent()” .

Q17. What are the types of windows in WPF?


Answer-
WPF has three types of windows:-
a)Normal Window
b)Page Window
c)Navigate Window

Q18. How can elements in a ListBox be sorted?


Answer-Sorting can be done by using a property of the ItemsCollection object.
ItemsCollection contains an attribute, SortDescriptions, which holds System.
ComponentModel.SortDescription instances. Every SortDescription instance defines how the
elements should be sorted and indicates if the sort is descending or ascending.

A list box is a graphical control element that allows the user to select one or more items
from a list contained within a static, multiple line text box

For instance, this code sorts elements of ContentControl on the basis of their word
count property:

myItemsControl.Items.SortDescriptions.Add(new SortDescription(“WordCount”,
ListSortDirection.Descending));

Q19. How is MVVM different from MVC?


Answer-MVC stands for Model-View Controller and.MVVM stands for Model-View
ViewModel.

In MVVM, View Model is used instead of a controller. This View Model is present beneath
the UI layer. It reveals the command objects and data that the view requires. It acts like
a container object from which the view gets its actions and data.
Model–view–controller (MVC) is a software design pattern commonly used for developing
user interfaces that divides the related program logic into three interconnected elements.

This is done to separate internal representations of information from the ways


information is presented to and accepted from the user.

Q20. Explain Routed events in WPF.


Answer-An event, which can invoke handlers on more than one listeners present in an
element tree, instead of the single object which called the event, is known as a Routed
event.

Q21. How is System.Windows.Media.Visual dll utilized in WPF?


Answer-It is used whenever a requirement for creating a custom user interface arises. It is a
drawing object, which gives instructions for making an object.
These instructions include opacity etc. of the drawing. The Visual class also bridges the
functionalities of WPF managed classes and the MilCore.dll.

Dynamic-link library is Microsoft's implementation of the shared library concept in the


Microsoft Windows and OS/2 operating systems. These libraries usually have the file
extension DLL, OCX, or DRV

Q22. What are the various layout panels in WPF?


Answer-They are:
Stack Panel-The StackPanel is very similar to the WrapPanel, but with at least one
important difference: The StackPanel doesn't wrap the content.

Grid Panel- A Grid panel can be used to design complicated user interfaces where we need
to place multiple elements in a tabular form of rows and columns layout.

Canvas Panel-A Canvas panel is used to position child elements by using coordinates that
are relative to the canvas area.

Dock Panel-The DockPanel makes it easy to dock content in all four directions (top, bottom,
left and right.

Wrap Panel- WPF WrapPanel control is a panel that positions child elements in sequential
position from left to right by default.
Q23. Name the important subsystems in WPF
Answer-The major subsystems are:

Windows.Controls.Control
Windows.DependancyObject
Windows.FrameworkElement
Windows.Media.Visuals
Object
Threading.DispatcherObject
Windows.UIElements

Q24. What does BAML mean in WPF?


Answer-BAML is the abbreviation for Binary Application Markup Language. It is nothing but
XAML that has been tokenized, parsed and changed into binary form.

BAML is a compressed declarative language, which gets loaded and parsed quicker than
XAML.

Q25. What is the Difference between Page and Window Controls in WPF?
Answer-
The basic difference is that Window Control presides over Windows Application while Page
Control presides over the hosted Browser Applications. Also, Window control may
contain Page Control, but the reverse cannot happen.

Q26. What are Attached Properties in WPF?


Answer-Attached properties are basically Dependency Properties that allow the attachment
of a value to any random object.
Q27. What is the INotifyPropertyChanged Interface?
Answer-The InotifyPropertyChanged notifies clients, generally those who are binding,
if the value of a property gets changed.

It has an event, calledPropertyChanged, which gets raised everytime a property of Model


object is changed.

Q28. What is the basic difference between Events and Commands in the MVVM
Model?
Answer-Commands are more powerful and are advantageous to use instead of
events. Actions are deeply connected with the event’s source and, therefore, the events
cannot be reused easily.

But commands make it possible to efficiently maintain multiple actions at one place
and then reuse them as per our requirement.
Q29. What is the method to force close a ToolTip, which is currently visible?
Answer-It can be closed by setting the tooltip’s IsOpen property to false.

Q30. Write the differences between DynamicResource and StaticResource.


Answer-The most basic difference is that StaticResource evaluates the resource one time
only, but DynamicResource evaluates it every time the resource is required.

And due to this reason, Dynamic Resource is heavy on the system but it makes pages
or windows load faster

Q31. Explain MVVM pattern.


Answer-

MVVM pattern divides the UI code into 3 basic parts:


Model – It represents a set of classes, which contain data received from databases.

View – It is the code that agrees with the visual representation of the data.
ViewModel – It is the layer that binds View and Model together. It presents this data in a
manner, which is easy to understand. It also controls how View interacts with the application.

Q32. Why are layout panels needed in WPF?


Answer-Layout Panels are needed so that the controls fit screens of different sizes or
having different font sizes. If we arrange controls on fixed pixel coordinates, then this
model will fail when moved to a different environment.

Q33. Write about UserControl in brief.


Answer-UserControl wraps existing controls into a single reusable group. It contains a
XAML file and a code.

UserControl cannot be styled or templated.


User controls are containers into which you can put markup and Web server controls. You
can then treat the user control as a unit and define properties and methods for it.
Custom controls.

Q34. What is the way to determine if a Freezable object is Frozen?


Answer-“IsFrozen” property of the object can be used to determine if the freezable object
is frozen.

Q35. What is the unit of measurement in WPF?


Answer-All measurements are made in device-independent pixels, or logical pixels. One
pixel is 1/96th part of an inch.

These logical pixels are always mentioned as double, this enables them to have a
fractional value too.

Q36. What is an adorner?


Answer-They are a special kind of FrameworkElement that provide visual clues to the user.
They are also used to add handles to elements and give information about the state of a
control.

Adorners are bound to the UIElement and are rendered on a surface that lies above
the element, which is adorned.

This surface is called an AdornerLayer. Adorners are mostly placed relatively to the
bounded element.

Q37. Explain Serialization?


Answer-It is the process of converting the state of an object to stream of bytes.
Q38. Is MDI supported in WPF?
Answer-MDI is not supported in WPF. UserControl can be used to give the same
functionality as MDI.

Q39. What is XBAP?


Answer-XBAP is the abbreviated form of XAML Browser Application. It allows WPF
applications to run inside web browsers. Installation of .NET framework on the client
machine is a prerequisite for running WPF applications.

But hosted applications are not given full admission to the client’s machine and are
executed in a sandbox environment. Using WPF, such applications can also be created,
which run directly in the browser. These applications are called XBAP.

Q40. In what sense are WPF and Silverlight similar?


Answer-Silverlight and WPF are similar in the sense that they both use XAML and share the
same code, syntax and libraries.

Q41. How to make a ToolTip appear while hovering over a disabled element?
Answer-For this purpose, the ShowOnDisabled property can be used. It belongs to the
ToolTipService class.

Q42. How can ListBox be made to scroll smoothly?

Answer-ListBox is configured to scroll on an item-by-item basis by default. This is


dependent on the height of each element and the scrolling action, thus, giving a rough
feeling. Better way is to configure the scrolling action so that it shifts items by a few
pixels irrespective of their height.

This is done by setting the ScrollViewer.CanContentScroll property to “false”. This will,


however, make the ListBox lose the virtualization property.

Q43. Where does the execution start in a WPF application?


Answer-WPF applications created in Visual Studio run without a Main method. This is
because the applications are special-cased when they are compiled from XAML. That
means, Visual Studio attaches a Build Action of ApplicationDefinition to the XAML file. This
results in the auto generation of a Main method.

Q44. Can Windows Service be created Using WPF?


Answer-No, Windows Services cannot be created using WPF. WPF is a presentation
language. Windows services need specific permissions to execute some GUI related
functions. Therefore, if it does not get the required permissions, it gives errors.

Q45. What are the different kinds of Routed events in WPF?


Answer-There are three types of Routed events in WPF. They are:
Direct – This event can only be raised by the element in which it was originated.

Tunneling – This event is first raised by the element in which it was originated and then it
gets raised by each consecutive container in the visual tree.

Bubbling – This event is first raised by the uppermost container in the visual tree and then
gets raised by each consecutive container lying below the uppermost one, till it reaches the
element it where it was originated.

Q46. Why is it better to wrap items in ComboBoxItem?


Answer-It has some important properties like IsSelected and IsHighlighted and also some
necessary events like Selected and Unselected.

ComboBoxItem is a content control and is thus very useful for adding simple strings
to a ComboBox.
Q47. How to get Automation IDs of items in an ItemsControl?
Answer-The best way to do this is by setting it Name property as it is utilized for automation
purposes by default.

But if you require to give an ID to an element, other than it’s name, then the
AutomationProperties.AutomationID property can be set as per need.

Q48. How can command-line arguments be retrieved in a WPF application?


Answer-The most preferred method for this is to call
System.Environment.GetCommandLineArgs at any random point in the application.

Q49. State the name of the classes, which contain arbitrary content.
Answer-
Content Control

HeaderedContent Control
Items Control
HeaderedItems Control

Q50. Which NameSpace has ‘Popup’ and ‘Thumb’ controls?


Answer-The namespace system.windows.controls.primitives has ‘Popup’ and ‘Thumb’
controls.

Q51. Explain what is XAML? What is the difference between XML and XAML?
Answer-XAML stands for eXtensible Application Markup Language. It is the language used
to instantiate.NET objects. It is the language developed by Microsoft to write user
interface for next generation applications.
XML is designed to store data or to work with the stored data, whereas XAML is the
extended version of XML used for.NET programming.

Q52. Mention the advantage of using XAML?


Answer-The advantage of using XAML is

XAML code is clear to read, and they are short


Separation of designer code and logic
Tools like expression blend used for graphical design require XAML as source
It clearly separates the roles of designer and developer

Q53. How can you code to display “Hello World” in XAML?


Answer-Displaying “Hello World.”
<page xmlns= '' ''>

<TextBlock>

Hello, World!

</TextBlock>

</Page>

Q54. In XAML how graphic components are specified?


Answer-In XAML, graphic components are specified by open or closed tags with attributes.
For example,

Tag with contents


<Button>

Click

</Button>

Tag without contents


< Button/>

Q55. What is Attribute Syntax in XAML?


Answer-In XAML, attribute syntax sets a value for a property or names the event handler for
an event, by declaring an attribute on an element. The attribute value should be enclosed
within two quotation marks (“).

For example,

< Button Background = “Black” Foreground “Red” Content = “This is an operating


button”/>

XAML

Q56. Explain Content Properties XAML?


XAML represents a language feature whereby a class can allot exactly one of its properties
as XAML property
Q57. Explain what is Markup extension in XAML?
Answer-Markup extensions are placeholders in XAML that are used to resolve property at
runtime. A markup extension allows you to extend XAML and using attribute syntax you can
also set any property that can be set in XAML.

The purpose of the mark up extension is to process a string and return an object.
Some of the standard markup extensions are xNull, x: Array, :StaticResource and
DynamicResource.

Q58. What are the four general kinds of XAML elements?


Answer-The four general kind of XAML elements are

Root Elements
Panel Elements
Control Elements
Geometric Elements

Q59. What X: prefix indicates in XAML?


Answer-The X: prefix is used to map the XAML namespace in templates.
Q60. What are the various X: prefix used in the XAML language?
Answer-x: Key It sets a unique key for each resource in a Resource Dictionary

x: Class It specifies the CLR ( Common Language Runtime) namespace and class name for
the class that provides code
x: Name It specifies a run-time object name for the instance that exist in run time code after
an object element is processed
x: Static It enables a reference that returns a static value which otherwise an XAML
compatible property
x: Type It constructs a Type reference based on the type name

Q61. How can you set a property attribute as a literal string and not a markup
extension?
Answer-To avoid markup extension you have to use an empty pair of curly braces like

Content = “{} {This is not a markup extension}”/>

Q62. What are the types of children does object element can have in XAML?
Answer-Three types of children an object element can have

Collection Items
A value for the content property
The value that can be type-converted to the object element

Q63. Explain what is Type Converter?


Answer-The type converter is helpful to convert a string into the appropriate value type
where there is no markup extension usage. Type Converter defines four members for
converting to and from string for xaml purposes.

CanConvertTo
CanConvertFrom
ConvertTo
ConvertFrom

Q64. Explain Object Element Syntax in XAML?


Answer-To instantiate a CLR class or structure by declaring an XML element, an XAML
markup syntax is used. This syntax is referred as Object Element Syntax.

Q65. What are the ways you can declare objects in XAML?
Answer-To declare objects in XAML, there are three ways-
Directly, using object element syntax: This syntax is used to declare root objects or nested
objects that set property values
Indirectly by using attribute syntax: This syntax uses an inline string value which has
an instruction on how to create an object. To set the value of the property to a newly
created reference, the XAML parser uses this string
Using a markup extension
Q66. What should a root element of an XAML document contain?
Answer-In XAML document, the root element consists only certain elements, and these
elements are Window, a Canvas or panels.

Q67. What is data binding with XAML?


Answer-Data binding provides a simple way to display and interact with data. An example
will show how you can do data binding in XAML. The binding in XAML is done by using
{binding….} syntax.

Q68. Explain how you can display different data at run time and design time?
Answer-One way of displaying data at run time and design time is to declare your data in
XAML
Another way of doing it is by declaring it in XAML by using various data attributes from the
designer XML namespace. With a d: prefix, this namespace is typically declared.
xmlns: d= http://schemas.microsoft.com/expression/blend/2008

Q69. Explain what is the function x: Key directive in XAML?


Answer-X: Key uniquely identifies elements that are created and referenced in an XAML
defined dictionary. By adding an x: Key value to an XAML object element a resource in the
resource dictionary can be identified and is the most common way to identify.

Q70. Explain what is the use of property element syntax?


Answer-With the help of property element syntax, you can add children element with a
name in the form of parent.propertyName.

Q71. How custom classes used in XAML can be defined?


Answer-Custom classes are used in two ways-
With the code that produces the Primary Windows Presentation Foundation (WPF)
application or within the code behind
In a separate assembly as a class, such as an executable or DLL used as a class
library

Q72. What is Xaml Namespace?


Answer-Namespace can be defined as an environment or an abstract container used to
hold a logical grouping of unique identifiers or symbols.

Q73 What is Content Alignment in WPF?


Answer- The content of content controls in WPF is dealt with using various properties.
These two properties are HorizontalContentAlignment and VerticalContentAlignment.

Q74 What are Resources in WPF?


Answer: Windows Presentation Foundation (WPF) resources provide a simple way to
reuse commonly defined objects and values. Resources in WPF allow you to set the
properties of multiple controls at a time. For example, you can set the background
property on several elements in a WPF application using a single resource.
Q75 What are static and dynamic resources?
Answer-There are two types of resource, namely,

Static Resource We should use the StaticResource markup extension to define the
resource as a static resource.
Dynamic Resource We use in a situation where we want to change the value of property at
run time.
Q76 How can you explain the view and view model in MVVM?
Answer: The View is the client interface, input-output interface or the user interface. It
collects all the user interface elements of the window, navigation page, user control,
resource file, style and themes, custom tools and controls.

The view is unaware of the ViewModel and the Model, and vice versa the ViewModel
and Model is unaware of the View and control is tightly decoupled.

Q77 What is Command Design Pattern and ICommand in WPF?


Answer: Command pattern is one of the most powerful design patterns in object
oriented design patterns. This pattern allows you to decouple the request of an action from
the object that actually performs an action, in other words a command pattern represents an
action as an object.

Q 78 What is the Data Binding concept and How Binding works in WPF?
Answer: Data Binding is one of the greatest and most powerful features of XAML (WPF,
Silverlight, Windows Phone or Windows 8) compared to other traditional web and Windows
app technology in .NET. There was simple data binding for displaying single values, and
complex data binding for displaying and formatting a bunch of data.

Q79 What is Trigger and how many types of triggers in WPF?


Answer: A Trigger is typically used in a Style or Control Template. It triggers on properties
of whatever is being templated, and sets other properties of the control (or of specific
template elements).

For example, you would use a Trigger on IsMouseOver to respond to the mouse being over
the control, and the setters might update a brush to show a "hot" effect.

There are five types of triggers supported by WPF; they are:


1.Property Trigger
2.Data Trigger
3.MultiTrigger
4.MultiDataTrigger
5.Event Trigger

Q80 What are the Binding Modes in XAML?


Answer: The DataBinding mode defines the communication direction to the source or the
direction of data flow from the source. In XAML there are five ways you can bind a data
target object to a source.

Q81 What are the Templates in WPF ?


Answer: Templates are an integral part of user interface design in WPF. WPF has the
following three types of templates:
1.Control Template
2.Items Panel Template
3.Data Template
Q82 What are Attached Properties in WPF ?
Answer: Attached properties are basically Dependency Properties that allow the
attachment of a value to any random object. Attached Properties (AP) are again a kind of
Dependency Property (DP) in XAML.

Q83 What is Resource in WPF? How many types of resources in WPF?


Answer: Windows Presentation Foundation (WPF) resources provide a simple way to reuse
commonly defined objects and values. Resources in WPF allow you to set the properties of
multiple controls at a time.

For example, you can set the background property on several elements in a WPF
application using a single resource. The best way of defining the resources is on a Window
or Page element level. Any resource that you define for an element also applies to their child
elements of that element.

If you define a resource for the grid element, then the resource applies only to the child
elements of the grid element.
Group_VBNet_WINForm

1. What is Visual Basic WinForms?


Visual Basic WinForms is a framework for creating desktop
applications with a graphical user interface (GUI) using the
Visual Basic programming language.

2. What is the difference between a form and a control in Visual


Basic WinForms?
A form is a top-level window that serves as the main
container for controls, which are UI elements such as buttons,
labels, and textboxes.

3. How do you handle button click events in Visual Basic


WinForms?
Button click events can be handled by associating an event
handler method with the button's Click event.

4. Explain the concept of data binding in Visual Basic WinForms.


Data binding allows you to connect UI controls to data
sources, automatically synchronizing data between them.

5. How do you create a new instance of a form in Visual Basic


WinForms?
You can create a new instance of a form using the `New`
keyword, such as `Dim myForm As New MyForm()`.

6. What is the purpose of the MessageBox class in Visual Basic


WinForms?
The MessageBox class is used to display popup message
boxes with information, warnings, or error messages to the
user.

7. How do you handle exceptions in Visual Basic WinForms


applications?
Exceptions can be handled using try-catch blocks to catch
and handle errors gracefully, providing appropriate error
messages or actions.

8. Explain the role of the Timer control in Visual Basic


WinForms.
The Timer control allows you to perform actions at regular
intervals, enabling you to create timed events or perform
periodic tasks.

9. How do you validate user input in Visual Basic WinForms?


User input can be validated using validation controls or by
manually checking the input and displaying error messages if
necessary.
10. What is the role of the BackgroundWorker class in Visual
Basic WinForms?
The BackgroundWorker class enables you to perform lengthy
or resource-intensive tasks on a separate thread, keeping the UI
responsive.

11. Explain the concept of MDI (Multiple Document Interface) in


Visual Basic WinForms.
MDI allows multiple child forms to be contained within a
parent form, providing a convenient way to work with multiple
documents or windows.

12. How do you save and retrieve application settings in Visual


Basic WinForms?
Application settings can be saved and retrieved using the
My.Settings object, which allows you to store and access user-
specific or application-wide settings.

13. What are the different layout options available in Visual


Basic WinForms?
Visual Basic WinForms provides various layout options,
including FlowLayoutPanel, TableLayoutPanel, and Anchor/Dock
properties, for organizing and positioning controls on a form.
14. How do you handle mouse and keyboard events in Visual
Basic WinForms?
Mouse and keyboard events can be handled by associating
event handler methods with the respective events, such as
MouseClick or KeyPress.

15. Explain the role of the OpenFileDialog and SaveFileDialog


controls in Visual Basic WinForms.
The OpenFileDialog control allows users to browse and select
files, while the SaveFileDialog control enables users to specify a
file location for saving.

16. How do you print documents in Visual Basic WinForms?


Printing documents can be accomplished using the
PrintDocument class and handling the PrintPage event to
define the document content.

17. What is the purpose of the ToolTip control in Visual Basic


WinForms?
The ToolTip control allows you to provide helpful tooltips or
hints for controls by displaying them when the mouse hovers
over the control.

18. How do you customize the appearance of controls in Visual


Basic WinForms?
Control appearance can be customized by modifying
properties such as BackColor, ForeColor, Font, and applying
custom styles using ControlStyles.

19. Explain the concept of event-driven programming in Visual


Basic WinForms.
Event-driven programming is a paradigm where the flow of
program execution is driven by events and event handlers,
responding to user actions or system events.

20. What is the role of the ErrorProvider control in Visual Basic


WinForms?
The ErrorProvider control is used to indicate validation errors
by displaying an icon or error message next to the control.
Group_VBNet_WebForm
1. What is the difference between ViewState and SessionState
in VB.NET Web Forms?
ViewState stores control state, while SessionState stores user-
specific data in VB.NET Web Forms.

2. Explain the concept of Master Pages in VB.NET Web Forms.


Master Pages provide a consistent layout and structure for
multiple web pages in VB.NET Web Forms.

3. How do you handle user authentication and authorization in


VB.NET Web Forms?
User authentication and authorization can be handled using
ASP.NET's membership and role management system in VB.NET
Web Forms.

4. What is the purpose of the App_Code folder in a VB.NET Web


Form application?
The App_Code folder is used to store code files that are
automatically compiled and accessed by other parts of the
application in VB.NET Web Forms.

5. Explain the difference between Server-side and Client-side


validation in VB.NET Web Forms.
Server-side validation is performed on the server, while client-
side validation is performed in the user's browser using
JavaScript in VB.NET Web Forms.

6. How do you handle concurrent updates to the same


database record in a VB.NET Web Form application?
Concurrent updates to the same database record can be
managed using locking or optimistic concurrency in VB.NET
Web Forms.

7. Describe the usage of the DataGrid and GridView controls in


VB.NET Web Forms.
The DataGrid and GridView controls are used for displaying
tabular data with sorting, paging, and editing features in
VB.NET Web Forms.

8. How do you implement caching in VB.NET Web Forms to


improve application performance?
Caching can be implemented using output caching or fragment
caching to improve performance in VB.NET Web Forms.

9. Explain the difference between GET and POST methods in the


context of VB.NET Web Forms.
The GET method sends form data in the URL, while the POST
method sends it in the request body in VB.NET Web Forms.
10. What are the advantages and disadvantages of using stored
procedures in VB.NET Web Forms?
Stored procedures offer advantages such as improved
performance and security but can be more complex to maintain
in VB.NET Web Forms.

11. How do you implement file uploading and downloading in


VB.NET Web Forms?
File uploading and downloading can be implemented using file
upload controls and providing download links or streams in
VB.NET Web Forms.

12. Explain the concept of AJAX and how it can be used in


VB.NET Web Forms.
AJAX allows asynchronous server requests and partial page
updates, enhancing user experience in VB.NET Web Forms.

13. How do you handle errors and exceptions in VB.NET Web


Forms applications?
Errors and exceptions can be handled using try-catch blocks to
display error messages and log details in VB.NET Web Forms.

14. Explain the usage of the ViewState and ControlState


properties in VB.NET Web Forms.
ViewState stores control state, while ControlState stores critical
control state information in VB.NET Web Forms.

15. How do you handle user input and prevent cross-site


scripting (XSS) attacks in VB.NET Web Forms?
User input should be validated on the server side to prevent
cross-site scripting attacks in VB.NET Web Forms.

16. Describe the usage of the Repeater and DataList controls in


VB.NET Web Forms.
The Repeater and DataList controls are used for displaying
repeated data from a data source in VB.NET Web Forms.

17. How do you implement pagination in VB.NET Web Forms to


display a large number of records?
Pagination can be implemented to display a large number of
records by retrieving subsets of data in VB.NET Web Forms.

18. Explain the difference between the Response.Redirect and


Server.Transfer methods in VB.NET Web Forms.
Response.Redirect redirects the user to a different page, while
Server.Transfer transfers control to a different page on the
server in VB.NET Web Forms.
19. How do you implement cascading dropdowns in VB.NET
Web Forms?
Cascading dropdowns can be implemented by populating child
dropdowns based on the selected value of parent dropdowns in
VB.NET Web Forms.

20. Describe the concept of connection pooling in the context


of VB.NET Web Forms and its benefits.
Connection pooling improves performance by reusing database
connections in VB.NET Web Forms.

21. How do you handle session timeouts in VB.NET Web Forms


applications?
Session timeouts can be handled by setting session timeout
values and redirecting to a login page in VB.NET Web Forms.

22. Explain the usage of the Authentication and Authorization


elements in the web.config file for securing VB.NET Web Forms
applications.
The Authentication and Authorization elements in the
web.config file are used to secure VB.NET Web Forms
applications.

23. How do you implement URL rewriting in VB.NET Web Forms


for search engine optimization (SEO) purposes?
URL rewriting is used for SEO purposes by rewriting web page
URLs in VB.NET Web Forms.

24. Describe the concept of ViewState encryption and its


importance in VB.NET Web Forms.
ViewState encryption enhances security by encrypting
ViewState data in VB.NET Web Forms.

25. How do you implement role-based access control (RBAC) in


VB.NET Web Forms applications?
Role-based access control can be implemented to restrict
access based on user roles in VB.NET Web Forms.

26. Explain the concept of caching techniques like Output


Caching and Fragment Caching in VB.NET Web Forms.
Output caching and fragment caching are caching techniques
used to improve performance in VB.NET Web Forms.

27. How do you handle cross-site request forgery (CSRF) attacks


in VB.NET Web Forms applications?
CSRF attacks can be prevented by using anti-forgery tokens
and implementing security measures in VB.NET Web Forms.

28. Describe the usage of the BulletedList and CheckBoxList


controls in VB.NET Web Forms.
The BulletedList and CheckBoxList controls are used for
displaying lists with bullet points and checkboxes in VB.NET
Web Forms.

29. How do you implement data binding in VB.NET Web Forms


using data source controls?
Data binding can be implemented using data source controls to
bind data to controls in VB.NET Web Forms.

30. Explain the usage of the UpdatePanel control and partial


page updates in VB.NET Web Forms.
The UpdatePanel control enables partial page updates using
AJAX in VB.NET Web Forms.

31. What is the purpose of the Application_Start event in


Global.asax file in VB.NET WebForms?
The Application_Start event is triggered when the application
starts and is used to perform application-level initialization
tasks.

32. Explain the concept of session state modes in VB.NET


WebForms.
Session state modes determine how session data is stored and
managed, with options like InProc, StateServer, and SQLServer.
33. How do you handle cross-page posting in VB.NET
WebForms?
Cross-page posting allows data to be transferred between
multiple pages using the PostBackUrl property and accessing
the PreviousPage property.

34. What is the purpose of the Trace feature in VB.NET


WebForms?
The Trace feature allows developers to track and debug
application execution by providing detailed information about
page rendering and control events.

35. Explain the role of the ConnectionString property in


database connectivity in VB.NET WebForms.
The ConnectionString property specifies the details required to
establish a connection with a database, including server name,
credentials, and database name.

36. How do you implement form-based authentication in


VB.NET WebForms?
Form-based authentication can be implemented using the
FormsAuthentication class to authenticate users based on
provided credentials.

37. What is the difference between a user control and a custom


server control in VB.NET WebForms?
A user control is a reusable control created by combining
existing controls, while a custom server control is a control built
from scratch by inheriting from the Control class.

38. Explain the usage of the DataReader and DataSet in data


access scenarios in VB.NET WebForms.
The DataReader provides a forward-only, read-only stream of
data from a database, while a DataSet is an in-memory
representation of data that can be manipulated and used for
disconnected data access.

39. How do you handle file and folder permissions in VB.NET


WebForms?
File and folder permissions can be managed using the File and
Directory classes, providing methods to set access control rules
and permissions.

40. Explain the usage of the ImageButton control in VB.NET


WebForms.
The ImageButton control is used to display an image that acts
as a clickable button, allowing image-based interactions in a
web form.

41. What are the different types of state management in VB.NET


WebForms?
The different types of state management in VB.NET WebForms
include ViewState, SessionState, ApplicationState, and Cookie-
based state management.

42. How do you implement custom error pages in VB.NET


WebForms?
Custom error pages can be defined in the web.config file using
the <customErrors> element to handle and display specific
error messages to users.

43. Explain the concept of postback and how it is handled in


VB.NET WebForms.
Postback refers to the process of submitting a web form to the
server for processing. In VB.NET WebForms, postback events
are automatically handled by the framework to trigger
appropriate server-side event handlers.

44. What is the purpose of the Calendar control in VB.NET


WebForms?
The Calendar control provides a graphical interface for selecting
dates and working with date-related functionalities in a web
form.

45. How do you implement globalization and localization in


VB.NET WebForms?
Globalization and localization can be implemented by using
resource files and culture-specific settings to display content in
different languages and adapt to regional preferences.

46. Explain the usage of the WizardStep control in VB.NET


WebForms.
The WizardStep control is used to define individual steps in a
wizard-like interface, allowing users to navigate through a
multi-step process.

47. How do you handle query strings in VB.NET WebForms?


Query strings can be accessed and processed using the
Request.QueryString collection to retrieve and utilize values
passed in the URL.

48. What is the purpose of the Placeholder control in VB.NET


WebForms?
The Placeholder control acts as a container that can hold other
controls dynamically, allowing dynamic content rendering in a
web form.

49. Explain the concept of data source controls in VB.NET


WebForms.
Data source controls provide a way to connect and interact with
data sources, such as databases, XML files, or web services, and
facilitate data binding and manipulation.
50. How do you implement custom paging in a GridView
control in VB.NET WebForms?
Custom paging in a GridView control can be achieved by
handling the GridView's PageIndexChanging event and
manually managing the data source based on the requested
page index.
Group_ASPNetCore_MVC_CSharp
Group_ASPNetCore_MVC_CSharp

Q1> What MVC (Model View Controller) architecture?

=> MVC is ServerSide Technology follows Front Controller pattern,


This Architectural Pattern consists of 3 parts i.e Model, View and Controller.

Model business layer, the part of the application that handles the logic for the application
data lies between View and Controller.

View represents User interface for MVC application where we HTML controls to interact
with User. We use HTML Helper Classes to design UI.

Controller It’s the major building block in MVC, inherited by “Controller” Class Which
provides features like Action Filter, Partial View, View Data, Temp Data etc.
Q2> How is it different from ASp.Net ?

Comparison to its Predecessor ASP.Net (Active Server Pages) which is Page Controller
pattern, which is also used for creating Web Applications. Note: ASP is also ServerSide
Technology

In MVC we integrate other technologies like JavaScript, jQuery, Bootstrap Entity framework
etc to create Responsive Web Pages.

Q3> What are Responsive Web Pages?


=> Responsive web pages are web pages that adapt and adjust their layout and design based
on the device and screen size they are being viewed on.
This ensures that the website looks and functions well on various devices, such as desktop
computers, laptops, tablets, and smartphones

Q4> Why MVC or Diff between ASP.Net?


=> MVC provides clear clean separation of code Compared to AspNet. It has features like
Model Binder, Action Filters and Routing etc.. ASP.NET MVC combines the benefits of
MVC pattern with the features of the ASP.NET framework,with a structured and
maintainable codebase.

Q5> Project Structure of MVC Application/Template?

=>
Solution-
The top-level container that represents the entire project solution. It contains one or more
projects and solution files (.sln)

Root –The "wwwroot" folder is where static files such as CSS, JavaScript, images, and other
client-side assets are stored. These files are directly accessible by the client browser.

Controller –
This folder or project section contains the controller classes that handle the incoming HTTP
requests, perform actions, and prepare data to be rendered in the views.

Controllers typically follow the naming convention of <Name>Controller.cs

Models –
The "Models" folder or project section holds the classes that represent the data structures,
entities, or business objects used within the application.

View-
The "Views" folder or project section contains the Razor views responsible for rendering the
HTML and generating the user interface.

appsettings.json –
This file contains configuration settings of the application. It helps to store config
information.
Here we can store info like database connection string, application variable values etc.

program.cs –
It is your application’s entry point which starts when you run your application. Here you
create your application host, choose the web server, add services, authorization and
authentications.

Dependencies-
This section shows the dependencies of the selected project, including NuGet packages,
project references, and other external libraries or frameworks used in the application.

Properties:
The "Properties" folder or section contains project-specific settings and metadata files. It may
include files like "launchSettings.json", which defines the launch profiles for the application.

Q6> What are the Advantages of MVC?

Multiple view support: Multiple views of the same data can be displayed at the same time.
Parallel Development: The development progresses in parallel

SOC Separation of Concerns: Separation of Concerns is one of the core advantages of


ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business
Logic, Model or Data.

Controls: The ASP.NET MVC framework provides more control over HTML, JavaScript,
and CSS than the traditional Web Forms.

Lightweight : ASP.NET MVC framework doesn’t use View State and thus reduces the
bandwidth of the requests to an extent.

SEO-friendly development: Improving its visibility and ranking in search engine results.
Code Reusability: With MVC, the separation of concerns allows for greater code reusability.
For example, you can reuse the same model or business logic across multiple views or
interfaces.

Enhanced Testability: Due to the separation of concerns, each component in MVC can be
tested independently.

Flexibility and Scalability: MVC provides a flexible and scalable architecture for
applications.
As the codebase grows, it becomes easier to add new features, modify existing functionality,
or extend the application's capabilities without affecting other components. The modularity of
MVC allows for easier maintenance and updates.

Support for Multiple Views: In MVC, the same model can be associated with multiple
views, each representing a different presentation of the data. This allows for greater
flexibility in supporting different user interfaces or platforms, such as desktop, web, or
mobile applications, without duplicating the underlying logic.

Areas of benefits in using MVC?

=> The area of benefits of using MVC is:


• Unit testing becomes much easier.
• It permits its users to shape views, models, and controllers into 3 distinct operational
sections within an application.
• It becomes easy to assimilate with other ar
• eas produced by another application
• It enables parallel development
Q7> What are the drawbacks of the MVC model?
=> Here are some important drawbacks of the MVC model:

• The model pattern is a little complex compared to ASP.net.


• Inefficiency of data access in view.
• You need multiple programmers for parallel development.
• Multiple technology knowledge is required.

Q8> How can we achieve clean separation of code in MVC?


=>
(Model-View-Controller) architectural design pattern
Model: Keep the data and business logic in the model. It should be responsible for managing
data and enforcing rules.
View: The view should focus solely on the presentation of data. Avoid placing complex logic
in the view and keep it separate from the model and controller.
Controller: The controller should handle user input, update the model, and choose the
appropriate view to display. It should not contain complex business logic.

Q9> MVC Application Life Cycle. /Can you explain the Request Life cycle of an
MVC application?
=> The life cycle of an MVC application involves the following steps:

-The user sends a request to the controller.


-The controller receives the request and invokes the appropriate action method.
-The action method interacts with the model to perform necessary operations.
-The action method selects an appropriate view to render.
-The view generates the response and sends it back to the user.

Step 1 - Fill route


MVC requests are mapped to route tables which in turn specify which controller and action to
be invoked. So if the request is the first request the first thing is to fill the rout table with
routes collection. This filling of the route table happens the global.asax file

Step 2 - Fetch route

Depending on the URL sent “UrlRoutingModule” searches the route table to create
“RouteData” object which has the details of which controller and action to invoke.
Step 3 - Request context created
The “RouteData” object is used to create the “RequestContext” object.

Step 4 - Controller instance created


This request object is sent to “MvcHandler” instance to create the controller class instance.
Once the controller class object is created it calls the “Execute” method of the controller
class.
Step 5 - Creating a Response object
This phase has two steps executing the action and finally sending the response as a result to
the view.

Q10> What is Routing in ASP.NET MVC /Url Routing?


Routing in ASP.NET MVC is a pattern matching system that maps the incoming requests
from the browser to specified actions of the MVC controller. When the application of
ASP.NET MVC gets started, it registers one or multiple patterns with the framework route
table so that it can inform the routing engine that what has to be done with the requests that
are matching with those patterns. When a request is received by the routing engine during
runtime, it matches that URL of the request against its registered URL patterns and provides
the response based on a pattern match.
For example, the URL pattern "{controller}/{action}/{id}" will look similar to
localhost:1234/{controller}/{action}/{id}.
Anything that comes after the"localhost:1234/" will be considered as the name of the
controller.
In the same manner, anything that comes after the controller name will be considered
as the name of the action and then comes the id parameter value.

Route Table:
Q11> How to manage the life cycle of objects or components within the application?
1.Scoped: A scoped object/component is created and maintained within the scope of a
specific request or user session. In other words, a new instance of the scoped object is created
for each request or session and is available throughout the lifetime of that request or session.
2.Transient: A transient object/component is created each time it is requested and is not
shared across different parts of the application. In other words, a new instance is created
every time you need it.
3.Singleton: A singleton object/component is created only once and is shared across the
entire application. It means that the same instance of the singleton object is reused whenever
it is requested.
Q12> What are strongly typed models in MVC?
=> Strongly typed models are classes that represent the data passed between the controller
and the view.
Q13> Define Scaffolding in MVC?

=> Scaffolding can be defined as an ASP.NET’s code-generation framework used in web


applications.. Scaffolding can also lower the quantity of time for developing a standard data
operation in the application.

Q14> How can you implement AJAX functionality in MVC?

=> AJAX functionality can be implemented in MVC by using the jQuery.ajax() method or
the AjaxHelper class to send asynchronous requests and update parts of the page
dynamically.

Q15> How many types of File extensions in razor views?


=> The different file extensions that are used by razor views are:
• .cshtml: When your MVC application is using C# as the programming language.
• .vbhtml: When your MVC application is using VB is the programming language

Q16> What is Razor ?


=> Razor View engine is a markup syntax which helps us to write HTML and server-side
code in web pages using C#

It is a view engine that combines HTML markup with server-side code to generate the final
HTML output. Razor provides a concise and expressive syntax for embedding server-side
code within HTML, making it easier to create dynamic and data-driven web applications.

Q17> What is used to handle an error in MVC?


=> Error handling is usually done using Exception handling, whether it’s a Windows Forms
application or a web application. The HandleError attribute is used, which helps in
providing built-in exception filters. The HandleError attribute of ASP.NET can be
functional over the action method as well as Controller at its global level.

Example of implementation:

public static void RegGlobalFilters(Global_FilterCollection filt)


{
filt.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
AreaRegn.RegisterAllAreas();
RegGlobalFilters(Global_Filters.Filters);
RegisterRoutes(Route_Table.Routes);
}

Q18> How can you implement authentication and authorization in MVC?

=> You can implement authentication and authorization in MVC by using authentication
filters, authorization attributes.

Q19> How can you enable client-side validation in MVC?


=> Client-side validation can be enabled in MVC by including the necessary JavaScript files
(jQuery Validation) and enabling unobtrusive validation.
Q20> What is the ModelState in MVC?

=> The ModelState represents the state of a model and its validation errors. It is an instance
of the ModelStateDictionary class.

Q21> How can you perform form validation in MVC?

=> Form validation can be performed in MVC by using data annotations, implementing
custom validation attributes, or by manually validating the form data.

Q22> What is HTML Helper/ Why Html Helper.?


In Traditional ASP.Net web form Application, we have Toolbox for adding Controls on
Particular Web page, However, in ASP.NET MVC application We don’t have such toolbox
available to drag and drop HTML controls onto the view.
So, the developers, Use HTML Helper Classes to create views in the ASP.NET MVC
application.
All the HtmlHelper methods that are present within the HtmlHelper class generate HTML
controls and return the result as an HTML string.
Overall, HTML Helper in ASP.NET MVC is an extension method of the HTML Helper class
which is used to generate HTML content in a view. @Html.TextBox(“firstname”)

In case, we Want to pass Class and other properties to TextBox Class.


@Html.TextBox(“firstname”, “Pranaya”, new { @class = “redtextbox”,
@readonly=”true” }

Q23> What is the Advantage of HTML Helper?


=> Using HTML Helper extension methods greatly reduces the amount of HTML code that
we write within a View/Design file.
Using HTML Helpers, you can generate HTML elements such as forms, input fields, links,
and more, while also handling things like URL routing, model binding, and validation. They
promote code reusability and help ensure consistent and semantically correct HTML output
across the application.
Q24> Syntax Diff Between Control Code in Html Helper, Html Control and Stored
Typed Html Helper.?

Also, while creating template for MVC, we have option to select languages like VB.Net, J#,
C# etc, same for the view .cshtml etc.

Q25> Features of MVC Framework


=> Model Binder: Its interface/Contract or connect HTML Form and Model Class in MVC
Framework.
It’s a mechanism that maps the HTTP request data with a model Class.
The values from View to the Model class are done by the Model Binder of MVC.
forms automatically get its data into model class.

ASP.NET MVC uses default binders to complete this behind the scenes.
then use the following HTML Helper method
Syntax: @Html.Hidden(“id”)

Model Binder makes it easier to get Form Values.

Q26> What is a postback?


A postback will occur when clients make a request for a server response from their viewing
page. Consider a simple example of a form completion by the user and hitting the “submit”
button. In this case, the property IsPostBack will be true, so the request will be processed by
the server and a response will be sent back to the client.

Q27> Explain briefly what you understand by separation of concern.

=> Separation of Concerns can be defined as one of the core features as well as benefits of
using MVC and is supported by ASP.NET. Here, the MVC framework offers a distinct
detachment of the different concerns such as User Interface (UI), data and the business logic.
Q28>What is used to handle an error in MVC?

=> Error handling is usually done using Exception handling, whether it’s a Windows Forms
application or a web application. The HandleError attribute is used, which helps in providing
built-in exception filters. The HandleError attribute of ASP.NET can be functional over the
action method as well as Controller at its global level.

Example of implementation:

public static void RegGlobalFilters(Global_FilterCollection filert)


{
filt.Add(new HandleErrorAttribute());
}

protected void Application_Start()


{
AreaRegn.RegisterAllAreas();
RegGlobalFilters(Global_Filters.Filters);
RegisterRoutes(Route_Table.Routes);
}

Q29> What is Hidden field?


Hidden fields are useful when you need to pass data between different parts of your application
or store data temporarily without displaying it to the user. They provide a way to maintain state
or transfer information between different requests or pages in a simple and efficient manner.
Q30> What are different Ways to get Values from MVC View?
=> Form Collection

Model Binder

Q31> Different return types used by the controller action method in MVC
Q: Action Result in MVC:
=> Action Result is a return type of Action method. Base of for all return types of all Action
Methods

Ex: View, Partial View, Redirect, Json, Content, File, Redirect To Action, etc. are derived
from the abstract Action Result class .

2. ViewResult – Represents HTML and markup


3. PartialViewResult – Represents HTML and markup.

4. EmptyResult – Represents no result

5. RedirectResult – Represents a redirection to a new URL

6. RedirectToActionResult – It is returning the result to a specified controller and


action method.

7. JsonResult – Represents a JavaScript Object Notation result that can be used in an


AJAX application.returns the data in JSON Format i.e. in the form of key-value pairs.
When we call this method using Ajax from a view. JsonResult is used to represent JSON-
encoded data, which is most commonly used to return structured data to a calling script,
especially in AJAX scenarios.
8. JavaScriptResult – Represents a JavaScript script.

9. ContentResult – Represents a text result.

10. FileContentResult – Represents a downloadable file (with the binary content).


11. FilePathResult – Represents a downloadable file (with a path).
12. FileStreamResult – Represents a downloadable file (with a file stream).
They all do the same work just there is a syntax difference for each result.

Q32>What is Partial View Result in ASP.NET MVC Application

=> It’s a Kind of User Control that can shared among different views.
When we have to return a Partial View instead of View from an Action Method in the ASP.NET
MVC Application. In that case we use Partial View Result.
The Partial View Result in MVC is returning the result to a Partial View Page.
A partial view is one of the views that we can call inside a normal view page.

Example of Partial View is “_layout.cshtml”.

Note: Normally, we keep Partial View inside the Shared Folder under View. So that it is
accessible to Controllers also the Controllers that are defined in Area. (Not mandatory)
Start with “_” under score.

_PartialView.cshtml: <h3>Its a Partial View</h3>

Q33> How We Can Add Partial View/ Steps to Add Partial View?
=> Right-Click on the Shared Folder which is inside the Views folder
and then selects Add => View option from menu
which will open the following Add view window, select “Create as Partial View”.
How We can Convert Objects to Json, string etc/ Ex of Json Action Result?

Q34>. What do you understand about Model Binding?


=> In action methods, we need to retrieve data from requests to be used by the data. In MVC,
model binding maps data from HTTP requests to action method parameters. This task of
retrieving data from HTTPRequest is repetitive and is removed from the action method

Q35>explain the concept of attribute routing?

=>With attribute routing, you can define routes right above the action methods in your
controllers using attributes, such as [Route] and [HttpGet]. This allows you to have more
control over the routing behavior and makes it easier to define custom routes for specific
actions.
Q36> Difference between attribute and conventional routing in mvc.

=> Conventional routing: The route is determined based on conventions that are defined in
route templates that, at runtime, will map requests to controllers and actions (methods).

Attribute-based routing: The route is determined based on attributes that you set on your
controllers and methods. These will define the mapping to the controller’s actions.

Q37> Mention what is the difference between adding routes to a webform application
and an MVC application?
Ans:
To add routes to a webform application, we can use MapPageRoute() method of the
RouteCollection class, where adding routes to an MVC application, you can use MapRoute()
method.

Q38> Explain briefly the GET and POST Action types?


• The GET Action Type is implemented for requesting the data from a particular
resource. Using these GET requests, a developer can pass the URL (that is
compulsory).
• The POST Action Type is implemented for submitting the data that needs to be
handled to a certain resource. Using these POST requests, a developer can move with
the URL, which is essential along with the data

Q39>explain the concept of asynchronous programming in ASP.NET MVC? When and


why would you use it?

=>Asynchronous programming in ASP.NET MVC involves using asynchronous methods


and operations to improve the scalability and responsiveness of web applications. It allows
you to perform tasks concurrently, without blocking the execution thread, which can
significantly enhance the performance of your application.

Some reasons to use asynchronous programming :


• Improved Scalability
• Enhanced Responsiveness
• Better Performance
• Avoiding Blocking Calls

In ASP.NET MVC, you can use the async and await keywords along with asynchronous
methods to perform asynchronous programming. Additionally, ASP.NET MVC provides
asynchronous versions of various I/O-bound operations, such as reading and writing to
databases or making HTTP requests, allowing you to take advantage of asynchronous
programming in different parts of your application.

Q40> How can you handle errors in MVC?

=> Errors can be handled in MVC by using try-catch blocks, implementing custom error
filters, or by using the HandleError attribute.
Q41> assembly in which the MVC framework

=> System.Web.Mvc, the MVC framework is usually defined.

Q42> How will you maintain the sessions in MVC?


=> The sessions of an MVC can be maintained in 3 possible ways:
• viewdata :The ViewData is a dictionary object that allows you to pass data from the
controller to the view. It is of type ViewDataDictionary.

• temp data

• view bag :The ViewBag is a dynamic property that allows you to pass data from the
controller to the view. It is a dynamic wrapper around the ViewData dictionary.

Q43>What is the difference between TempData and ViewBag/ViewData?


=> TempData is used to store data between two consecutive requests, whereas
ViewBag/ViewData are used to pass data from the controller to the view within the same
request.
Q44> What is the difference between ViewData and ViewBag?

=> ViewData is a dictionary object used to pass data between the controller and the view,
whereas ViewBag is a dynamic property that provides a similar functionality.

Q45>What is the need session management ?

=> Session management is a scenario for storage of user data while the user browses a web
Application.
Some reasons why session management is needed.
User Authentication- When a user logs in to a web application, their login credentials are
verified, and a session is created.
User State Management:Sessions enable the storage and management of user-specific data
and state across multiple requests
Security and Authorization-
Customization and Personalization:
E-commerce and Shopping Carts
Stateful Web Applications
Tracking and Analytic

Q46>What is a cookie ?

=> Cookies provide a means in Web applications to store user-specific information.


For example, when a user visits your site, you can use cookies to store user preferences or
other information. When the user visits your Website another time, the application can
retrieve the information it stored earlier
Types of Cookie
.Persistent Cookie: Persistent Cookie is a user specific cookie meaning it is stable after
closing the browser.It also allows the time duration for the maintaining the session.

.Non-Persistent Cookie: Non Persistent Cookie destroys when we close the browser.It is
Basically stateless in nature.

Q47> What is DOM, why is it used ?

=> DOM stands for Document Object Model. In simple terms, it's a way for web browsers
to understand and manipulate web pages.
DOM is a tool that enables web browsers to understand and manipulate web pages. It
provides a structured representation of the elements

Q48> What is HTTP verbs and How many types of HTTP verbs?
[HttpGet]:. It is used when you want a specific action to handle GET requests for a
particular route.
[HttpPost]: It is used for form submissions or any action that requires modifying data on the
server.
[HttpPut]:. It is typically used for updating existing resources on the server.
[HttpDelete]:. It is used for deleting resources on the server.
25. What does a context mean in http
=> It represents the environment and data that is necessary to process and handle the request
or response correctly.
• 1.Request context: The request context contains information related to the HTTP
request being made. It includes details such as the request method (e.g., GET, POST),
the requested URL, request headers, query parameters, cookies, and form data.

• 2.Response context: The response context contains information related to the HTTP
response being sent back to the client. It includes details such as the response status
code (e.g., 200 OK, 404 Not Found).

• 3.Session context: The session context represents the state and data associated with a
user's session. In HTTP, which is a stateless protocol, sessions are typically managed
using cookies or URL rewriting.
Q49> Why are Minification and Bundling introduced in MVC?

=> Two new techniques have been included in MVC, known as Bundling and minification,
whose primary function is to progress the request load time. It advances the load time by
dipping the number of requests sent to the server as well as reducing the requested asset’s
(JavaScript and CSS) size.

Q50> concept of Filters in MVC?

=> There are situations where I want to implement some logic either prior to the execution of
the action method or right after it. In that scenario, the Action Filters are used. Filters are used
to determine the logic needed for executing before or after the action method gets executed.
Action methods make use of the action filters as an attribute.

Different types of MVC action filters are:


• Action filter (that implements the IActionFilter).
• Exception filter (that implements the IExceptionFilter attribute).
• Authorization filter (that implements the IAuthorizationFilter).
• Result filter (that implements the IResultFilter

=> The order in which filters are used:


First, the Authorization filters are executed.
Followed by the Action filters.
Then, the Response filters are executed.
Finally, the Exception filters.

Q51> What are Action filters in ASP.NET MVC?


Action filters are the additional attributes in the ASP.NET MVC framework, that we can
apply to either a section of the controller or to the entire controller The following action
filters are provided by ASP.NET MVC:
• Output Cache: This action filter will cache the controller action output for a
specified time.
• Handle Error: This action filter will handle the errors raised during the execution of
a controller action.
• Authorize: This action filter will enable you for restricting to a particular role or user.

Q52> What “beforeFilter()”,”beforeRender” and “afterFilter” functions do in


Controller?
=>
• beforeFilter(): This function runs before every action in the controller. It’s the right
place to check for an active session or inspect user permissions.
• beforeRender(): This function is called after controller action logic, but before the
view is rendered.
• afterFilter(): This function is called after every controller action and after rendering
is done. It is the last controller method to run.

Q53> Partial view of MVC?

What is the difference between View and Partial View?


=> Here is the difference between View and Partial View

View Partial View

It contains the layout page It does not contain the layout page

Before any view is rendered, viewstart page Partial view does not verify for a
is rendered viewstart.cshtml. We cannot put common
code for a partial view within the
viewStart.cshtml.page

View might have markup tags like body, Partial view is designed specially to render
html, head, title, meta etc. within the view, and just because of that it
does not consist any markup

View is not lightweight as compare to We can pass a regular view to the


Partial View. RenderPartial method
Q54> What do you understand about ViewState in MVC?
=> MVC does not have ViewState. This is because ViewState is stored in a hidden field on
the page, which increases its size significantly and impacts the page loading time.

Q55> How is exception handling carried out in MVC?


=> We can override the ‘OnException' event in the controller and set the result to the view
name needed to be invoked when an error occurs.
Example:
public ActionResult Index()
{
int l = 1;
int m = 0;
int n = 0;
m = l / m; //it would cause an exception.
return View();
}
protected override void OnException(ExceptionContext filterContext)
{
string action = filterContext.RouteData.Values["action"].ToString();
Exception e = filterContext.Exception;
filterContext.ExceptionHandled = true;
filterContext.Result = new VR()
{
ViewName = "err"
};
}

Q56> Why do we need Dependency Injection ?


=> Dependency injection is a software design pattern that promotes loose coupling and
modularity in applications.e the dependencies of a class or a component are provided
externally, rather than being created or managed within the class itself.

Here are some reasons why dependency injection is beneficial:

• 1.Decoupling: helps decouple the components of an application. By injecting


dependencies, a class doesn't need to know how to create or obtain its dependencies.

• 2.Flexibility and Reusability: With dependency injection, components can be easily


reused in different contexts or scenarios.

• 3.Testability:, you can provide mock or stub implementations during testing, allowing
you to isolate and test individual components in isolation.

• 4.Separation of Concerns: Dependency injection helps separate the creation and


management of dependencies from the logic of the class.
Q57>What is the use of Middleware?
=> Middleware acts as a pipeline that intercepts and processes requests and performs
certain actions or transformations.
• 1.Request Processing: When a request is made to an MVC application, it first goes
through the middleware pipeline before reaching the appropriate controller.

• 2.Processing Actions: Each middleware component in the pipeline has the


opportunity to inspect and modify the request and perform specific actions.

• 3.Passing to Next Middleware: After performing its specific tasks, a middleware


component can either choose to pass the request to the next middleware component in
the pipeline or stop the pipeline and generate a response immediately.

• 4.Response Processing: Once the request has passed through all the middleware
components and reached the controller, the controller performs its actions and
generates a response.

Q58>How is WebApi is Different from mvc?


=> Purpose: MVC: MVC is a framework for building web applications that follow the
Model-View-Controller architectural pattern. It is primarily used for creating web
applications that have rich, interactive user interfaces and complex server-side processing
logic.
Web API: Web API is a framework for building HTTP services that can be consumed by
clients, such as web browsers, mobile apps, or other web services.
.Data Format: MVC: MVC typically uses HTML as the primary data format for rendering
views that contain the user interface components.
Web API: Web API is designed to work with various data formats, including JSON
(JavaScript Object Notation) and XML (eXtensible Markup Language).
3.View vs. Data: MVC focuses on generating views that define the user interface and
presentation logic. The views are responsible for rendering HTML markup and displaying
data to the user.
Web API: Web API focuses on providing data as the response to client requests. It is
primarily concerned with data access, serialization, and providing an interface for client
applications to interact with the data.
Q59>What is Output Caching in MVC

when we want to improve the performance of the application we use output caching, it
prevents the duplicate content to be loaded by caching the content returned by the controller,

When the controller methods are invoked, it is the best method to reduce the server round
trips, reduce database server round trips, reduce network traffic etc.

[HttpPost]
[OutputCache(Duration = 10, VaryByParam = "name")]
public ActionResult SearchCustomer(string name = "")
{
NorthwindEntities db = new NorthwindEntities();
var model = from r in db.Customers
where r.ContactName.Contains(name)
select r;
if (model.Count() > 0)
{
return View(model);
}
else
{
return View();
}
}
Q60>Explain RenderSection In MVC

RenderSection is used to designate a place to render content that is different from the one in
RenderBody.
Example:
@RenderSection("footer", required: false)
By default, a section is required. We pass required: false to designate that section is optional.
@Section is used to render section in View as:
@section Footer
{
<p>Section/Index page</p>
}
Group_React_AspNetCore
Q.1. What is the difference between Virtual DOM and Real DOM?
Ans. Virtual DOM Real DOM
Changes can be made easily Changes can be expensive
Minimal memory wastage High demand for memory and more wastage

JSX element is updated Creates a new DOM every time an element if the
element exists gets updated
Cannot update HTML directly Able to directly manipulate HTML
Faster updates Slow updates

2. What is React?
• React is a front-end JavaScript library developed by Facebook in 2011.
• It follows the component based approach which helps in building reusable
UI components.
• It is used for developing complex and interactive web and mobile UI.
• Even though it was open-sourced only in 2015, it has one of the largest
communities supporting it.

3. What are the features of React?


Major features of React are listed below:
i. It uses the virtual DOM instead of the real DOM.
ii. It uses server-side rendering.
iii. It follows uni-directional data flow or data binding.

4. List some of the major advantages of React.


Some of the major advantages of React are:

iv. It increases the application’s performance


v. It can be conveniently used on the client as well as server side
vi. Because of JSX, code’s readability increases
vii. React is easy to integrate with other frameworks like Meteor, Angular, etc
viii. Using React, writing UI test cases become extremely easy

5. What are the limitations of React?


Limitations of React are listed below:

ix. React is just a library, not a full-blown framework


x. Its library is very large and takes time to understand
xi. It can be little difficult for the novice programmers to understand
xii. Coding gets complex as it uses inline templating and JSX

6. What is JSX?
JSX is a shorthand for JavaScript XML. This is a type of file used by React which
utilizes the expressiveness of JavaScript along with HTML like template syntax.
This makes the HTML file really easy to understand. This file makes applications
robust and boosts its performance. Below is an example of JSX:
render(){
return(

<div>

<h1> Hello World from </h1>

</div>

);
}
7. What do you understand by Virtual DOM? Explain its works.
A virtual DOM is a lightweight JavaScript object which originally is just a copy of
the real DOM. It is a node tree that lists the elements, their attributes and content
as Objects and their properties. React’s render function creates a node tree out of
the React components. It then updates this tree in response to the mutations in
the data model which is caused by various actions done by the user or by the
system.

8. Why can’t browsers read JSX?


Browsers can only read JavaScript objects but JSX in not a regular JavaScript object.
Thus to enable a browser to read JSX, first, we need to transform JSX file into a
JavaScript object using JSX transformers like Babel and then pass it to the browser.

9. How different is React’s ES6 syntax when compared to ES5?


Syntax has changed from ES5 to ES6 in the following aspects:

xiii. require vs import

1 // ES5
2 var React = require('react');
3
4 // ES6
5 import React from 'react';

xiv. export vs exports

1 // ES5
2 module.exports = Component;
3
4 // ES6
5 export default Component;

xv. component and function

1 // ES5
2 var MyComponent =
React.createClass({
3
render: function() {
4
return
5
6
7 <h3>Hello Edureka!</h3>
8 ;
9 }
10 });
11
12 // ES6
13 class MyComponent extends
React.Component {
14
render() {
15
return
16
17
<h3>Hello Edureka!</h3>
18
;
19
}
}

xvi. props

1 // ES5
2 var App = React.createClass({
3 propTypes: { name:
React.PropTypes.string },
4
render: function() {
5
return
6
7
<h3>Hello,
8
{this.props.name}!</h3>
9
;
10
}
11
});
12
13 // ES6
14 class App extends
React.Component {
15
render() {
16
return
17
18
<h3>Hello,
19
{this.props.name}!</h3>
20
;
}
}

1 // ES5
2 var App = React.createClass({
3 getInitialState: function()
{
4
return { name: 'world'
5
};
6
},
7
render: function() {
8
return
9
10
<h3>Hello,
11 {this.state.name}!</h3>
12 ;
13 }

14 });
15
16 // ES6
17 class App extends
React.Component {
18
19 constructor() {
20 super();
21 this.state = { name:
'world' };
22
}
23
render() {
24
return
25
26
<h3>Hello,
{this.state.name}!</h3>
;
}
}

10. How is React different from Angular?


React vs Angular

TOPIC REACT ANGULAR


1. ARCHITECTURE Only the View of MVC Complete MVC
2. RENDERING Server-side rendering Client-side rendering
3. DOM Uses virtual DOM Uses real DOM
4. DATA BINDING One-way data binding Two-way data binding
5. DEBUGGING Compile time debugging Runtime debugging
6. AUTHOR Facebook Google

11. “In React, everything is a component.” Explain.


Components are the building blocks of a React application’s UI. These
components split up the entire UI into small independent and reusable pieces.
Then it renders each of these components independent of each other without
affecting the rest of the UI.

12. What is the purpose of render() in React.


Each React component must have a render() mandatorily. It returns a single React
element which is the representation of the native DOM component. If more than
one HTML element needs to be rendered, then they must be grouped together
inside one enclosing tag such as <form>, <group>,<div> etc. This function must
be kept pure i.e., it must return the same result each time it is invoked.

13. How can you embed two or more components into one?
We can embed components into one in the following way:
1 class MyComponent extends
React.Component{
2
render(){
3
return(
4
5
<div>
6
7
<h1>Hello</h1>
8
9
<Header/>
10
</div>
11
12
);
13
}
14
}
15
class Header extends
16
React.Component{
17
render(){
18
return
19
20
<h1>Header Component</h1>
21
22
};
23
}
24
ReactDOM.render(
25 <MyComponent/>,
document.getElementById('content
')
);

14. What is Props?


Props is the shorthand for Properties in React. They are read-only components
which must be kept pure i.e. immutable. They are always passed down from the
parent to the child components throughout the application. A child component
can never send a prop back to the parent component. This help in maintaining
the unidirectional data flow and are generally used to render the dynamically
generated data.

15. What is a state in React and how is it used?


States are the heart of React components. States are the source of data and must
be kept as simple as possible. Basically, states are the objects which determine
components rendering and behavior. They are mutable unlike the props and
create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.


States vs Props

Conditions State Props

1. Receive initial value from parent component Yes Yes

2. Parent component can change value No Yes

3. Set default values inside component Yes Yes

4. Changes inside component Yes No

5. Set initial value for child components Yes Yes

6. Changes inside child components No Yes

17. How can you update the state of a component?


State of a component can be updated using this.setState().
1 class MyComponent extends
React.Component {
2
constructor() {
3
4 super();

5 this.state = {
6 name: 'Maxx',

7 id: '101'
8 }

9 }

10 render()
11 {
12
setTimeout(()=>{this.setState({name
13
:'Jaeha', id:'222'})},2000)
14
return (
15
16
<div>
17
18
<h1>Hello {this.state.name}</h1>
19

20
<h2>Your Id is {this.state.id}</h2>
21

22
</div>
23

24
);
25
}
26
}
27
ReactDOM.render(

<MyComponent/>,
document.getElementById('content')

);

18. What is arrow function in React? How is it used?


Arrow functions are more of brief syntax for writing the function expression. They
are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the
context of the components properly since in ES6 auto binding is not available by
default. Arrow functions are mostly useful while working with the higher order
functions.
1 //General way

2 render() {
3 return(

4 <MyInput
onChange={this.handleChange.bind(th
5
is) } />
6
);
7
}
8
//With Arrow Function
9
render() {
10
return(
11
<MyInput onChange={ (e) =>
12 this.handleOnChange(e) } />
);
}

19. Differentiate between stateful and stateless components.


Stateful vs Stateless

Stateful Component Stateless Component

1. Stores info about component’s state change in 1. Calculates the internal state of the
memory components

2. Have authority to change state 2. Do not have the authority to change state

3. Contains the knowledge of past, current and 3. Contains no knowledge of past, current and
possible future changes in state possible future state changes

4. Stateless components notify them about the 4. They receive the props from the Stateful
requirement of the state change, then they send components and treat them as callback
down the props to them. functions.

20. What are the different phases of React component’s lifecycle?


There are three different phases of React component’s lifecycle:
xvii. Initial Rendering Phase: This is the phase when the component is
about to start its life journey and make its way to the DOM.
xviii. Updating Phase: Once the component gets added to the DOM, it can
potentially update and re-render only when a prop or state change occurs.
That happens only in this phase.
xix. Unmounting Phase: This is the final phase of a component’s life cycle
in which the component is destroyed and removed from the DOM.

21. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

xx. componentWillMount() – Executed just before rendering takes place both


on the client as well as server-side.
xxi. componentDidMount() – Executed on the client side only after the
first render.
xxii. componentWillReceiveProps() – Invoked as soon as the props are
received from the parent class and before another render is called.
xxiii. shouldComponentUpdate() – Returns true or false value based on
certain conditions. If you want your component to update, return true else
return false. By default, it returns false.
xxiv. componentWillUpdate() – Called just before rendering takes place in
the DOM.
xxv. componentDidUpdate() – Called immediately after rendering takes
place.
xxvi. componentWillUnmount() – Called after the component is
unmounted from the DOM. It is used to clear up the memory spaces.

22. What is an event in React?


In React, events are the triggered reactions to specific actions like mouse hover,
mouse click, key press, etc. Handling these events are similar to handling events
in DOM elements. But there are some syntactical differences like:

xxvii. Events are named using camel case instead of just using the
lowercase.
xxviii. Events are passed as functions instead of strings.

The event argument contains a set of properties, which are specific to an event.
Each event type contains its own properties and behavior which can be accessed
via its event handler only.
23. How do you create an event in React?
1 class Display extends
React.Component({
2
show(evt) {
3
// code
4
},
5
render() {
6
// Render the div with
7
an onClick prop (value is a
8 function)
9 return (

10
11 <div onClick={this.show}>Click
Me!</div>
12
13
);
}
});

24. What are synthetic events in React?


Synthetic events are the objects which act as a cross-browser wrapper around the
browser’s native event. They combine the behavior of different browsers into one
API. This is done to make sure that the events show consistent properties across
different browsers.

25. What do you understand by refs in React?


Refs is the short hand for References in React. It is an attribute which helps to
store a reference to a particular React element or component, which will be
returned by the components render configuration function. It is used to return
references to a particular element or component returned by render(). They come
in handy when we need DOM measurements or to add methods to the
components.
1 class ReferenceDemo extends
React.Component{
2
display() {
3
4 const name =
this.inputDemo.value;
5
6
document.getElementById('disp').
7 innerHTML = name;
8 }

9 render() {
10 return(

11
12 <div>
13 Name: <input
type="text" ref={input =>
14
this.inputDemo = input} />
15
<button name="Click"
16 onClick={this.display}>Click</bu
tton>
17
18
<h2>Hello <span
id="disp"></span> !!!</h2>

</div>
);
}
}

26. List some of the cases when you should use Refs.
Following are the cases when refs should be used:

• When you need to manage focus, select text or media playback


• To trigger imperative animations
• Integrate with third-party DOM libraries

27. How do you modularize code in React?


We can modularize code by using the export and import properties. They help in
writing the components separately in different files.

1 //ChildComponent.jsx
2 export default class
ChildComponent extends
3
React.Component {
4
render() {
5
return(
6
7
<div>
8
9
<h1>This is a child
10 component</h1>
11
12 </div>

13
14 );

15 }

16 }
17
18 //ParentComponent.jsx
19 import ChildComponent from
'./childcomponent.js';
20
class ParentComponent extends
21
React.Component {
22
render() {
23
return(
24
25
<div>
26
<App />
27
</div>
28

);
}
}

28. How are forms created in React?


React forms are similar to HTML forms. But in React, the state is contained in the
state property of the component and is only updated via setState(). Thus the
elements can’t directly update their state and their submission is handled by a
JavaScript function. This function has full access to the data that is entered by the
user into a form.

1 handleSubmit(event) {
2 alert('A name was submitted:
' + this.state.value);
3
event.preventDefault();
4
}
5
6
render() {
7
return (
8
9
<form
10
onSubmit={this.handleSubmit}>
11
<label>
12
Name:
13
<input
14 type="text"
value={this.state.value}
15
onChange={this.handleSubmit} />
16
</label>
17
<input type="submit"
18 value="Submit" />
</form>

);
}

29. What do you know about controlled and uncontrolled components?


Controlled vs Uncontrolled Components
Controlled Components Uncontrolled Components
1. They do not maintain their own state 1. They maintain their own state
2. Data is controlled by the parent
2. Data is controlled by the DOM
component
3. They take in the current values through
props and then notify the changes via 3. Refs are used to get their current values
callbacks

30. What are Higher Order Components(HOC)?


Higher Order Component is an advanced way of reusing the component logic.
Basically, it’s a pattern that is derived from React’s compositional nature. HOC are
custom components which wrap another component within it. They can accept
any dynamically provided child component but they won’t modify or copy any
behavior from their input components. You can say that HOC are ‘pure’
components.

31. What can you do with HOC?


HOC can be used for many tasks like:

• Code reuse, logic and bootstrap abstraction


• Render High jacking
• State abstraction and manipulation
• Props manipulation

32. What are Pure Components?


Pure components are the simplest and fastest components which can be written.
They can replace any component which only has a render(). These components
enhance the simplicity of the code and performance of the application.

33. What is the significance of keys in React?


Keys are used for identifying unique Virtual DOM Elements with their
corresponding data driving the UI. They help React to optimize the rendering by
recycling all the existing elements in the DOM. These keys must be a unique
number or string, using which React just reorders the elements instead of re-
rendering them. This leads to increase in application’s performance.

34. What were the major problems with MVC framework?


Following are some of the major problems with MVC framework:

• DOM manipulation was very expensive


• Applications were slow and inefficient
• There was huge memory wastage
• Because of circular dependencies, a complicated model was created
around models and views

35. Explain Flux.


Flux is an architectural pattern which enforces the uni-directional data flow. It
controls derived data and enables communication between multiple components
using a central Store which has authority for all data. Any update in data
throughout the application must occur here only. Flux provides stability to the
application and reduces run-time errors.

36. What is Redux?


Redux is one of the most trending libraries for front-end development in today’s
marketplace. It is a predictable state container for JavaScript applications and is
used for the entire applications state management. Applications developed with
Redux are easy to test and can run in different environments showing consistent
behavior.

37. What are the three principles that Redux follows?


xxix. Single source of truth: The state of the entire application is stored in
an object/ state tree within a single store. The single state tree makes it
easier to keep track of changes over time and debug or inspect the
application.
xxx. State is read-only: The only way to change the state is to trigger an
action. An action is a plain JS object describing the change. Just like state is
the minimal representation of data, the action is the minimal
representation of the change to that data.
xxxi. Changes are made with pure functions: In order to specify how the
state tree is transformed by actions, you need pure functions. Pure
functions are those whose return value depends solely on the values of

their arguments.

38. What do you understand by “Single source of truth”?


Redux uses ‘Store’ for storing the application’s entire state at one place. So all the
component’s state are stored in the Store and they receive updates from the Store
itself. The single state tree makes it easier to keep track of changes over time and
debug or inspect the application.

39. List down the components of Redux.


Redux is composed of the following components:

xxxii. Action – It’s an object that describes what happened.


xxxiii. Reducer – It is a place to determine how the state will change.
xxxiv. Store – State/ Object tree of the entire application is saved in the
Store.
xxxv. View – Simply displays the data provided by the Store.

In case you are facing any challenges with these React interview questions,
please comment on your problems in the section below.

40. Show how the data flows through Redux?


41. How are Actions defined in Redux?
Actions in React must have a type property that indicates the type of ACTION being
performed. They must be defined as a String constant and you can add more
properties to it as well. In Redux, actions are created using the functions called
Action Creators. Below is an example of Action and Action Creator:
1 function addTodo(text) {
2 return {

3 type: ADD_TODO,

4 text
5 }

6 }

42. Explain the role of Reducer.


Reducers are pure functions which specify how the application’s state changes in
response to an ACTION. Reducers work by taking in the previous state and action,
and then it returns a new state. It determines what sort of update needs to be
done based on the type of the action, and then returns new values. It returns the
previous state as it is, if no work needs to be done.

43. What is the significance of Store in Redux?


A store is a JavaScript object which can hold the application’s state and provide a
few helper methods to access the state, dispatch actions and register listeners.
The entire state/ object tree of an application is saved in a single store. As a result
of this, Redux is very simple and predictable. We can pass middleware to the store
to handle the processing of data as well as to keep a log of various actions that
change the state of stores. All the actions return a new state via reducers.

44. How is Redux different from Flux?


Flux vs Redux

Flux Redux

1. The Store contains state and change logic 1. Store and change logic are separate

2. There are multiple stores 2. There is only one store

3. All the stores are disconnected and flat 3. Single store with hierarchical reducers

4. Has singleton dispatcher 4. No concept of dispatcher

5. React components subscribe to the store 5. Container components utilize connect

6. State is mutable 6. State is immutable


45. What are the advantages of Redux?
Advantages of Redux are listed below:

• Predictability of outcome – Since there is always one source of truth, i.e.


the store, there is no confusion about how to sync the current state with
actions and other parts of the application.
• Maintainability – The code becomes easier to maintain with a predictable
outcome and strict structure.
• Server-side rendering – You just need to pass the store created on the
server, to the client side. This is very useful for initial render and provides a
better user experience as it optimizes the application performance.
• Developer tools – From actions to state changes, developers can track
everything going on in the application in real time.
• Community and ecosystem – Redux has a huge community behind it
which makes it even more captivating to use. A large community of talented
individuals contribute to the betterment of the library and develop various
applications with it.
• Ease of testing – Redux’s code is mostly functions which are small, pure
and isolated. This makes the code testable and independent.
• Organization – Redux is precise about how code should be organized, this
makes the code more consistent and easier when a team works with it

46. What is React Router?


React Router is a powerful routing library built on top of React, which helps in
adding new screens and flows to the application. This keeps the URL in sync with
data that’s being displayed on the web page. It maintains a standardized structure
and behavior and is used for developing single page web applications. React
Router has a simple API.

47. Why is switch keyword used in React Router v4?


Although a <div> is used to encapsulate multiple routes inside the Router. The
‘switch’ keyword is used when you want to display only a single route to be
rendered amongst the several defined routes. The <switch> tag when in use
matches the typed URL with the defined routes in sequential order. When the first
match is found, it renders the specified route. Thereby bypassing the remaining
routes.

48. Why do we need a Router in React?


A Router is used to define multiple routes and when a user types a specific URL, if
this URL matches the path of any ‘route’ defined inside the router, then the user
is redirected to that particular route. So basically, we need to add a Router library
to our app that allows creating multiple routes with each leading to us a unique
view.
1 <switch>

2 <route exact path=’/’


component={Home}/>
3
<route path=’/posts/:id’
4
component={Newpost}/>
5
<route path=’/posts’
component={Post}/>
</switch>

49. List down the advantages of React Router.


Few advantages are:

xxxvi. Just like how React is based on components, in React Router v4, the
API is ‘All About Components’. A Router can be visualized as a single root
component (<BrowserRouter>) in which we enclose the specific child
routes (<route>).
xxxvii. No need to manually set History value: In React Router v4, all we
need to do is wrap our routes within the <BrowserRouter> component.
xxxviii. The packages are split: Three packages one each for Web, Native and
Core. This supports the compact size of our application. It is easy to switch
over based on a similar coding style.

50. How is React Router different from conventional routing?


Conventional Routing vs React Routing

Topic Conventional Routing React Routing

PAGES Only single HTML page is


Each view corresponds to a new file
INVOLVED involved

A HTTP request is sent to a server


URL Only the History attribute is
and corresponding HTML page is
CHANGES changed
received

User is duped thinking he is


User actually navigates across
FEEL navigating across different
different pages for each view
pages
51. What is the difference between a controlled and uncontrolled
component in React?
In React, a controlled component is a component that has its state controlled by
the parent component. The parent component passes the state as props to the
controlled component and also handles any changes to the state via callback
functions. The controlled component only renders the received props and does
not have its own state.

An uncontrolled component, on the other hand, maintains its own internal state
and updates it using DOM events. The component directly updates the DOM and
does not rely on the parent component to pass and update the state.

An example of a controlled component is a form input that receives its value


from the parent component as a prop and updates the parent component’s
state via a callback function when the input is changed. An uncontrolled
component would be a form input that maintains its own internal state and
updates the value directly when the input is changed, without the need for a
callback function.

In general, controlled components are considered to be more predictable and


easier to debug than uncontrolled components. They also make it easier to
implement complex validation and error handling.

52. How do you handle forms in React?

Handling forms in React can be done in a few different ways, but the most
common approach is to create a controlled component for the form and its
inputs. A controlled component is a component that has its state controlled by
the parent component. The parent component passes the state as props to the
controlled component and also handles any changes to the state via callback
functions.

Here is an example of how to handle a simple form with two input fields
(username and password) in a controlled component:

22. First, define the initial state of the form in the parent component’s
constructor. For example:
1 </pre>

2 constructor(props) {
3 super(props);

4 this.state = {

5 username: '' ,
6 password: '',

7 };
8 }

9 <pre>

23. Next, create callback functions for each input field that updates the
corresponding state property when the input value changes. For example:

1 </span>
2 handleUsernameChange = (event) =

3 this.setState({username:
event.target.value});
4
}
5
handlePasswordChange = (event) => {
6
this.setState({password:
7
event.target.value});
}

3. Pass the state properties and callback functions as props to the


controlled form component. For example:
1 <Form

2 username={this.state.username}
3 password={this.state.password}

4 handleUsernameChange={this.handleUs
ernameChange}
5
handlePasswordChange={this.handlePa
6
sswordChange}
/>

24. In the controlled form component, use the passed-in props to set the
value and onChange attributes of each input field. For example:
1 <input
2 type="text"

3 value={props.username}

4 onChange={props.handleUsernameChang
e}
5
6 />

7 <input
8 type="password"

9 value={props.password}
10 onChange={props.handlePasswordChang
e}

/>

25. Finally, in the parent component’s form submit callback function, you can
access the form data from the component’s state and handle the form
submission as necessary.

Alternatively, you can use third-party libraries such as Formik, or the new hooks
in react, useState and useEffect, to handle forms in a more efficient way.

It’s important to note that when you are creating forms in React, you should also
validate the input values, and display appropriate error messages to users.

53. Explain the concept of a Higher Order Component (HOC) in React.

In React, a Higher Order Component (HOC) design is used to reuse component


logic. It is a function that accepts a component as an argument and outputs a
new component that extends the capabilities of the input component. Without
having to write duplicate code, HOCs can be used to add shared features, like
authentication and data retrieval, to various components. All of the original
component’s props as well as any extra props supplied to the HOC are
transferred to the wrapped component. HOCs are a potent method for
composing and enhancing pre-existing components without changing their
original source code.

54. What is the purpose of the mapStateToProps function in Redux?

The mapStateToProps function in Redux is a way for a component to access the


current state of the store and update its props accordingly. It does this by taking
the current state of the store as an argument and returning an object that maps
the state to the props of the component. The returned object is then passed to
the component as props, allowing it to access the state and re-render when the
state changes. This function is typically defined as a separate function outside of
the component and is passed as an argument to the connect function, which is
used to connect the component to the store.
55. How do you handle routing in a React application?

In a React application, routing is typically handled using a library such as React


Router. React Router allows you to define specific routes for different parts of
your application and map them to specific components. When the user
navigates to a specific route, the corresponding component is displayed on the
page.

For example, you could have a route for the homepage that maps to a “Home”
component and a route for a user’s profile that maps to a “Profile” component.
When the user navigates to the “/” route, the Home component would be
displayed, and when they navigate to the “/profile” route, the Profile component
would be displayed.

To use React Router in a React application, you’ll need to install it, import it into
your application, and define your routes and the components they map to.
Here’s an example of how you might set up React Router in a simple React
application:
1 import { BrowserRouter as Router,
Route } from "react-router-dom";
2
import Home from
3
“./components/Home";
4
import profile from
5 “./components/Profile”;
6 function App() {

7 return (
8 <Router>

9 <Route exact path="/"


component={Home} />
10
<Route path="/profile"”
11 component={Profile} />

</Router>

);
}

In this example, the Router component is used to wrap the entire application
and the Route component is used to define the specific routes and the
components they map to. The exact prop is used to ensure that only the exact
path is matched and not any subpaths.
56. Explain the difference between server-side rendering and client-side
rendering in React.

In a React application, there are two main ways to render the components:
server-side rendering (SSR) and client-side rendering (CSR).

Server-side rendering (SSR) is when the initial render of a React application is


done on the server. The server generates the HTML for the initial state of the
application and sends it to the browser. When the JavaScript bundle loads, React
takes over and the application continues to function as a SPA (Single-Page
Application) on the client side.

This approach has a few benefits such as:

Improved performance for search engines and users on slow connections

Faster time-to-first-byte

Better accessibility for users who have JavaScript disabled

Client-side rendering (CSR) is when the React application is rendered entirely in


the browser, using JavaScript. The browser requests the JavaScript bundle from
the server and then renders the components on the client side. This approach
has the benefit of faster load times for users on fast connections and a more
responsive user interface.

In general, CSR is the simpler option to implement and more popular, but SSR is
a good choice for certain use cases, such as when SEO is a primary concern, or
when the app is targeting users on slow internet connections.

It is also worth noting that, it is possible to have a hybrid approach between SSR
and CSR which is called isomorphic or universal rendering. This approach allows
to leverage the benefits of both SSR and CSR.

57. How do you handle data persistence in a React application?

In a React application, data persistence can be handled using a variety of


methods, including:
26. Local storage: This allows you to store key-value pairs in the browser’s
local storage, which can be retrieved even after the user closes the
browser or restarts their device.
27. Cookies: Cookies are small pieces of data that are stored in the user’s
browser and can be accessed by the website on subsequent visits.
28. IndexedDB: It’s a low-level API for client-side storage of large amounts of
structured data, including files/blobs.
29. Web SQL Database: This is a deprecated technology for storing data in a
client-side database using SQL.
30. Server-side storage: You can also store data on a remote server using an
API or a database such as MySQL, MongoDB, etc.
31. Redux or Mobx: State management libraries like Redux or Mobx can be
used to manage and persist application state across different components
and sessions.

Which one to use depends on your specific use case and requirements.

58. What is the difference between a stateless component and a stateful


component in React?

In React, a component can be either stateless or stateful. The main difference


between the two is how they manage and update their data.

A stateless component, also known as a “dumb” or “presentational” component,


is a component that does not maintain its own internal state. It receives data
and callbacks through props (short for properties) and only renders the UI based
on those props. Stateless components are typically used for simple,
presentational elements that don’t need to handle any complex logic or internal
state updates. They are simple functions that take props and return JSX.

A stateful component, also known as a “smart” or “container” component, is a


component that maintains its own internal state. It can handle internal state
updates and side effects, and may also manage the state of other child
components. Stateful components are typically used for more complex elements
that need to handle user interactions, API calls, or other logic. They are class
components that extend React.Component.

In general, it is recommended to use stateless components as much as possible


to keep the application simple and easy to understand. Stateful components
should only be used when it is necessary to manage state or handle complex
logic.
59. Explain the concept of a Pure Component in React.

A “pure component” in React is a component that updates only when its


properties or state have changed. In contrast, a “non-pure component” re-
renders each time the parent component re-renders, regardless of whether its
props or state have changed. Pure components are more productive since they
do not needlessly re-render. By extending React, a component in React can be
made pure. React is substituted by PureComponent. Component. This prompts
the shouldComponentUpdate method, which decides whether or not to re-
render, to provide an automatic shallow comparison of the component’s props
and state.

60. How do you handle optimization in a large React application?

There are several techniques that can be used to optimize a large React
application:

Use the React Developer Tools to identify and fix performance bottlenecks. The
React Developer Tools allow you to track the performance of individual
components and identify which components are causing the most re-renders.

Use the shouldComponentUpdate lifecycle method to prevent unnecessary re-


renders. This method allows you to control when a component should update
based on its props and state.

Use PureComponent and memo instead of Components. These are more


efficient alternatives to React.Component that only re-render when props or
state have changed.

Use the useEffect hook to handle side effects. This hook allows you to run side
effects, such as network requests, after a component has rendered.

Use the useMemo hook to memoize expensive calculations. This hook allows
you to cache the results of expensive calculations and only recalculate them
when the inputs have changed.

Lazy loading: Lazy loading is a technique where you only load the components
that are needed for the current view. This can greatly improve the performance
of your application.
Code splitting: Code splitting is a technique where you split your application into
smaller chunks of code that are loaded on demand. This can greatly improve the
performance of your application.

Optimize the loading time of your application by using techniques like code
minification, compression, and caching.

It’s also important to keep in mind that performance optimization is an ongoing


process and you should regularly check and optimize your application as it
grows.

61. What is the purpose of the combineReducers function in Redux?

The combineReducers function in Redux is used to combine multiple individual


reducers into a single root reducer. In a Redux application, the state is managed
by a single store and each piece of the state is managed by a specific reducer.
The combineReducers function takes an object whose keys correspond to the
keys in the state, and whose values are the individual reducers that will manage
those parts of the state.

The combineReducers function is used to compose the different reducers that


handle different parts of the state into a single root reducer. This root reducer is
then passed to the createStore function to create the Redux store.

The combineReducers function is also useful for structuring and organizing your
code in a more modular way, as it allows you to separate the logic for different
parts of the state into different files and functions.

The combineReducers function is not mandatory to use, but it makes it easier to


split the application state and the reducer functions that handle it in a more
modular way and also it helps to avoid name collision if you have multiple
reducer functions that handle a specific part of the state.

62. How do you handle error handling in a React application?

A React application can handle errors in a few different ways. To handle


problems that happen during rendering, one typical solution is to utilise a try-
catch block within a component’s lifecycle functions, such as
componentDidCatch. Use the Error Boundaries feature to design a component
that detects errors that happen inside its child components as an alternative
strategy. In addition, you may manage errors that happen inside a functional
component by combining the useEffect hook with a try-catch block.
There are several ways that an error can be handled in a React application. Using
a try-catch block in a component’s lifecycle routines, like componentDidCatch, is
a common way to manage rendering-related issues. An alternate approach is to
construct a component that detects problems that occur inside its child
components using the Error Boundaries feature. Additionally, you may control
errors that occur inside a functional component by combining a try-catch block
with the useEffect hook.

63. What is the difference between a smart component and a dumb


component in React?

Smart Component Dumb Component


Has state and logic Has no state or logic
Can communicate with other
Can only receive props and emit
components through props and
events
callbacks
Can make API calls or perform
Can only display data passed to it
complex logic
Typically class-based components Typically functional components

64. Explain the concept of a Render Prop in React.

A render prop in React is a technique for conveying component logic. Instead of


using a component’s props to communicate data and behaviour, a render prop
is a function that a component utilises to select what to render. The “provider”
component makes the render prop available, but the “consumer” component is
the one that uses it. With this approach, component flexibility and reuse are
enhanced.

65. How do you handle testing in a React application?

React Testing Library is a great tool for testing React components. It’s a set of
helpers that let you test React components without relying on their
implementation details. This approach makes refactoring a breeze and also
nudges you towards best practices for accessibility. With components, the
distinction between a “unit” and “integration” test can be blurry. If you’re testing
a form, should its test also test the buttons inside of it? Or should a button
component have its own test suite? Should refactoring a button ever break the
form test? Jest is a JavaScript test runner that lets you access the DOM via jsdom,
which is an approximation of how the browser works. Jest provides a great
iteration speed combined with powerful features like mocking modules and
timers so you can have more control over how the code executes. It’s a great
tool for running tests on React apps. You can also use a tool like BrowserStack’s
Real Device Cloud to run end-to-end tests on real devices. Cross browser
compatibility testing can also be done with a tool like BrowserStack Live.

66. What are the different ways to pass data between components in
React?

Data is passed as a property on the element when utilising props to


communicate between components. For instance, you can do the following to
send a user object from a parent component to a child component: The props
object, props.user, can then be used in the child component to access the data.
Data can be passed via the component tree using context rather than having to
go through each level of the tree. You must establish a context object containing
a Provider and a Consumer in order to use context.

The components that require the data are served by the Provider, and the
components that need to access the data are served by the Consumer. Data that
is local to a component can be stored in a state, which allows for the tracking of
data across time. Through the useState Hook, state in a component can be
obtained. The current state value and a function to update the state value are
the two items of an array that the useState Hook returns after receiving an initial
value.

67. Explain the concept of a Portal in React.

A React component can be rendered outside of the DOM hierarchy of its parent
component using React Portals. As an example, you could render components in
a modal dialogue box, hover card, loader, or popup message, which would be in
a “different place” than their parent component. The ReactDOM.createPortal()
method, which accepts a React element (child) and a DOM element as inputs, is
used to create React portals (container). The container is the DOM element that
the child component should be rendered into, and the child component is any
renderable React child, such as an element, string, or fragment. For items that
must appear above all other elements, such as profile hovercards, modal
dialogue boxes, and tooltips, portals are frequently utilised.

68. How do you handle performance optimization in a React application?


There are several ways to optimize the performance of a React application,
including:

• Using the shouldComponentUpdate lifecycle method to prevent


unnecessary re-renders of components.
• Using React’s built-in PureComponent or implementing a custom
shouldComponentUpdate method to optimize performance for functional
components.
• Using the React developer tools to profile the application and identify
performance bottlenecks.
• Using the React.memo method for functional components
• Using React’s Context API instead of props drilling.
• Using the useEffect hook to handle side effects in functional components.
• Using the useCallback and useMemo hooks to prevent unnecessary re-
renders and improve performance.
• Lazy loading of components and code splitting.
• Minimizing the number of DOM updates by using the key prop when
rendering a list of items.
• Using the useReducer hook to manage state updates instead of useState
• Using a virtualized list library like react-virtualized, react-window etc.
• It’s always a good idea to test performance with real-world use cases and
user interactions before and after making any optimization.

69. What is the difference between a functional component and a class


component in React?

In React, a functional component is a plain JavaScript function that takes in props


and returns a React element. A class component is a JavaScript class that
extends React.Component and has a render method that returns a React
element.

One key difference between the two is that a class component can have local
state and lifecycle methods, while a functional component cannot. However,
starting with React 16.8, functional components can also have a state using
hooks.

Functional components are considered simpler, easier to understand and test,


and have better performance than class components. Class components are
useful when you need to use lifecycle methods or the local state.
70. Explain the concept of a Context in React.

In React, context is a way to share data that is considered “global” for a


component tree. It allows you to pass data through the component tree without
having to pass props down manually at every level.

A component that needs to access the context data can consume it by using the
useContext hook or the Consumer component. To make the context available to
a component, a parent component needs to provide it using the Provider
component.

Context is often used for data that is required by many components in an


application, such as the currently authenticated user, the current locale, or the
theme.

It should be noted that context should be used sparingly, as it can make your
components more difficult to reason about and test. If possible, it’s better to
pass props down the component tree manually.

71. How do you handle asynchronous data loading in a React application?

In a React application, asynchronous data loading can be handled using a


technique called “lifting state up”. This involves moving the state that manages
the loading and error state of the data to a common ancestor component, and
passing down the necessary callbacks and state through props to the
components that need to use the data.

One popular way to handle async data loading is to use the useEffect hook in
combination with fetch or a library like axios to load data in a component after it
has been rendered. The useEffect hook allows you to synchronize a component
with an external system, such as a server, by running a side effect (the data
loading) after the component has rendered. The hook takes a callback function
that contains the effect, and an array of dependencies.

Another way is to use a library like redux-thunk or redux-saga to handle the


async request and store the data in the store/state. These libraries provide an
easy way to handle async actions and keep the component state clean.

In either case, it’s important to keep an eye on the component’s state and
update it properly with the loaded data.

A simple example of loading data asynchronously in a React component using


useEffect and fetch:
1 import { useState, useEffect } from
‘react’;
2
function MyComponent() {
3
const [data, setData] =
4
usestate(null);
5
const [error, setError] =
6 usestate(null);

7 const [loading, setloading] =


usestate(true);
8
useEffect(() => {
9
async function fetchData() {
10
try {
11
const response = await
12 fetch('https://example.com/data’);
13 const json = await response.json();

14 setData(json);
15 setLoading(false);

16 } catch (error) {

17 setError(error) {
18 setLoading(fase);

19 }
20 }

21 fetchData();

22 }, []);

if (loading) {

return <p>Loading...</p>;

1 if (error) {

2 return <p>Error:
{error.message}</p>;
3
}
4
return <p>Data:
5
{JSON.stringify(data)}</p>;
}

It’s important to note that this is a simple example, and in a real-world


application you may need to handle more complex cases such as pagination,
caching and handling different types of errors.

72. What is the difference between state and props in React?


State and Props are both concepts in React that are used to store and
manipulate data within a React component. The main difference between
the two is that State is used to store and manage the data that is local and
specific to a component, while Props are used to pass data from a parent
component to its child components.

State is considered to be dynamic, meaning that it can change over time as a


result of user interactions or other events. On the other hand, Props are
considered to be static and cannot be changed by the child component. Instead,
the parent component is responsible for updating the value of its Props and
passing the updated value to the child component.

In summary, State is used to manage the internal state of a component, while


Props are used to pass data from a parent component to its child components.

73. Explain the concept of a Hook in React.

“Hooks are a new feature in React that allows us to add state and other React
features to functional components. They were introduced in React 16.8 and have
since become a popular way to manage state and side effects in functional
components. Hooks are named functions that start with the word use and allow
us to reuse stateful logic across components without having to write a class
component. For example, the useState Hook allows us to add state to a
functional component and the useEffect Hook lets us perform side effects like
data fetching or updating the document title. Hooks make our code more
reusable, easier to understand, and easier to test.”

74. How do you handle localization in a React application?


Handling localization in a React application typically involves creating
translated versions of your text content and displaying the appropriate
version based on the user’s preferred language.

One way to handle localization in a React application is to use a library such as


react-i18next. This library provides a set of tools for internationalization and
localization, including the ability to define translation keys and their
corresponding translations, as well as providing a way to switch between
languages at runtime.

To use react-i18next in your React application, you would install it using npm
and then configure it in your index.js file. After that, you can use the
useTranslation Hook to access the translations in your components.

Here’s how you can explain localization in a React application in an interview:

“Localization in a React application involves creating translated versions of text


content and displaying the appropriate version based on the user’s preferred
language. To handle localization in a React application, I would use a library such
as react-i18next, which provides a set of tools for internationalization and
localization. With this library, I would define translation keys and their
corresponding translations and provide a way to switch between languages at
runtime. In my components, I would use the useTranslation Hook to access the
translations and display the appropriate version of the text content.”

75. What is the difference between a static component and a dynamic


component in React?
In React, a static component is a component that is defined with a fixed set
of properties or attributes and does not change during its lifecycle. A static
component is defined using a simple JavaScript function that returns a tree
of elements that represent the component’s UI.
A dynamic component, on the other hand, is a component that can change its
properties, state or behavior based on interactions with the user or events that
occur within the application. A dynamic component is typically defined using a
class component or a functional component with the useState or useEffect
Hooks.

Here’s an example of a static component:


1 function welcome(props) {

2 return <h1>Hello,
{props.name}</h1>;
3
}

76. Explain the concept of a Renderless Component in React.

A Renderless Component in React is a component that doesn’t render any HTML


elements to the DOM, but instead exposes data and methods to other
components through props and callbacks. The purpose of a renderless
component is to encapsulate logic that can be reused across multiple
components and keep the component tree lean and flexible. The other
components that consume the logic provided by a renderless component can
then render the HTML elements they need based on the information and
functionality they receive from the renderless component. This approach
separates the logic and presentation concerns, making the code easier to
maintain and test.

77. How do you handle server-side rendering in a React application?

Server-side rendering (SSR) in React involves rendering your React components


on the server and sending the resulting HTML to the client. This provides a
number of benefits, including improved performance and search engine
optimization (SEO). To implement SSR in a React application, you can use a
library like Next.js or Razzle, which provide an easy-to-use framework for
handling SSR. Alternatively, you can use the ReactDOMServer API to manually
render your components on the server. The key steps in the process are:

32. Setting up your server to handle incoming requests and render the
appropriate components.
33. Rendering the components on the server using
ReactDOMServer.renderToString or
ReactDOMServer.renderToStaticMarkup.
34. Sending the resulting HTML to the client as part of the response.
35. Hydrating the components on the client so that they can be interactively
controlled by the user.

It’s worth noting that SSR comes with some trade-offs and additional complexity,
so it’s important to carefully consider whether it’s the right choice for your
application.

78. What is the difference between a presentational component and a


container component in React?

In React, a presentational component (also known as a dumb component) is a


component that focuses on UI (user interface) and presentation of the data,
while a container component (also known as a smart component) is a
component that focuses on how the data is being managed and provides the
data for the presentational components.

A presentational component is typically written as a functional component,


receiving data as props and returning a view, while a container component is
typically written as a class component, handling data management and state
changes, and passing down the data to the presentational components as props.

The separation of concerns between the two types of components allows for
better code organization, maintenance, and testing.

79. Explain the concept of a Custom Hook in React.

A Custom Hook in React is a JavaScript function that lets you extract state logic
and behavior out of a component, and reuse it across multiple components.
Custom Hooks allow you to abstract away state and behavior that is common
across your application into a reusable piece of code.

Custom Hooks are named with the prefix use (e.g. useForm, useFetch), and can
call other Hooks as well as your own custom Hooks. They have the same rules as
Hooks and can only be called at the top level of your component or your own
custom Hooks.

Custom Hooks can receive arguments and return values, just like a regular
function, but they also have the ability to manage state and perform side-effects.
By abstracting state and behavior into a Custom Hook, you can improve the
readability and maintainability of your code.

Examples of things you can build with Custom Hooks include:

• Data fetching
• Managing state updates
• Handling form submissions
• Implementing animations and transitions
• And many more.

Using Custom Hooks can make your components cleaner, more reusable, and
easier to test, which makes them a powerful tool in your React toolkit.

80. How do you handle accessibility in a React application?

Handling accessibility in a React application involves making sure that your


application can be used by as many people as possible, including those with
disabilities. This can be achieved through various techniques, including:

36. Semantic HTML: Use semantic HTML elements, such as <button>, <nav>,
and <header>, to clearly define the structure and purpose of your
content.
37. Accessible Props: Use accessible props, such as aria-label, role, and
tabIndex, to provide additional information to assistive technologies, such
as screen readers.
38. Keyboard Navigation: Ensure that all functionality can be accessed using a
keyboard, and that keyboard focus is managed correctly.
39. Color Contrast: Make sure that the contrast between the text and the
background is high enough to be readable by people with color blindness
or low vision.
40. Alternative Text: Provide alternative text for images, videos, and other
non-text elements to ensure that information is accessible to screen
reader users.
41. Screen Reader Testing: Test your application with screen readers and
other assistive technologies to identify and fix any accessibility issues.

It is important to note that accessibility is a continuous process and should be


considered throughout the development of your React application. The use of
tools, such as linting rules and accessibility testing tools, can also help ensure
that your application is accessible.

81. What is the difference between a reducer and an action in Redux?

In Redux, a reducer and an action are two different but related concepts.

An action is a plain JavaScript object that describes the change that should be
made to the state of the application. It has a type property that defines the type
of action being performed, and a payload property that provides any additional
data needed to perform the action. Actions are dispatched from the application
to the Redux store, which then passes the action to the reducers.
A reducer is a pure function that takes the current state of the application and
an action, and returns the next state of the application. The reducer is
responsible for handling the actions and updating the state accordingly. It
should not perform any side-effects, such as making API calls, but should instead
only return the next state.

In summary, actions describe what should change, while reducers define how
the state should change in response to the actions.

82. Explain the concept of a Higher Order Component (HOC) in React and
when to use it.

A Higher Order Component (HOC) in React is a function that takes a component


as an argument and returns a new component with additional props. The
purpose of a HOC is to reuse logic across multiple components. An HOC is not a
“part” of React, it’s a pattern in React for reusing component logic.

Use a HOC when you need to:

• Share common logic between multiple components, such as data fetching


or authorization.
• Abstract state and behavior that can be reused across your application,
into a reusable HOC.
• Render a component within another component and pass props to the
wrapped component.

Examples of HOCs include the withRouter HOC from react-router and the
connect HOC from react-redux.

83. How do you handle data validation in a React application?

Data validation in a React application can be handled in a variety of ways,


including:

42. PropTypes: React provides a built-in library called PropTypes that allows
you to specify the expected data types for your component’s props.
PropTypes will validate the props passed to your component at runtime,
and will log warnings in the browser console if any props are of the wrong
type.
43. Custom validation functions: You can write custom validation functions to
check the validity of your data. These functions can be called inside your
component, and can be used to set error messages or update the state to
indicate invalid data.
44. Third-party libraries: There are several third-party libraries available for
data validation in React, such as yup, joi, or zod. These libraries provide a
more powerful and flexible way to validate data, and often provide a more
user-friendly way to report errors.

Regardless of the method you choose, it’s important to handle data validation in
your React application to ensure that the data being processed is in the correct
format and meets the required constraints. Validation helps to catch potential
errors early in the development process and prevent bugs from affecting the
end-user experience.

84. What is the difference between a synchronous action and an


asynchronous action in Redux?

In Redux, an action is a plain JavaScript object that describes the change in the
state of the application. Actions can be either synchronous or asynchronous.

A synchronous action is an action that is dispatched and immediately processed


by the Redux store. The store updates the state, and the updated state is
immediately available for consumption by the components.

An asynchronous action, on the other hand, is an action that is dispatched but


takes some time to complete. Asynchronous actions are typically used when
performing network requests or doing other operations that take time. These
actions cannot be immediately processed by the Redux store, so they require
additional logic to handle their completion.

In a Redux application, asynchronous actions are often handled using


middleware, such as redux-thunk or redux-saga, which allow for the dispatching
of actions that represent the start and completion of asynchronous operations.
These middleware provide a way to handle the asynchrony of the operation and
ensure that the state is updated appropriately once the operation is complete.

85. Explain the concept of a Virtual DOM in React.

A Virtual DOM (Document Object Model) is a lightweight in-memory


representation of the actual DOM in a web page. In React, the Virtual DOM acts
as an intermediary between the React component’s render output and the
browser’s DOM.

When a React component’s state changes, React updates the Virtual DOM,
instead of directly updating the actual DOM. This is more efficient because
updating the Virtual DOM is faster than updating the actual DOM, as it can
calculate the difference between the previous and current render output, and
only update the parts that have changed.

React then takes the updated Virtual DOM and uses it to update the actual DOM,
minimizing the amount of work that needs to be done in the actual DOM and
improving the overall performance of the application.

In summary, the Virtual DOM in React acts as an optimization to increase the


speed and efficiency of updates to the user interface.

86. How do you handle browser compatibility in a React application?

To handle browser compatibility in a React application, you can use various


techniques such as:

45. Polyfills: To support older browsers, you can use polyfills, which are
JavaScript libraries that emulate missing features in older browsers.
46. Browser detection: You can use libraries like browser-detect to detect the
user’s browser and its version, and adjust your code accordingly.
47. Feature detection: Instead of relying on browser detection, you can use
feature detection to check if a specific feature is supported by the user’s
browser before using it.
48. CSS Reset: You can use CSS resets like normalize.css to make sure that all
browsers display the styles in a consistent way.
49. Testing: Regular testing in different browsers and devices is essential to
catch any compatibility issues early in the development process.

By using these techniques, you can ensure that your React application runs
smoothly across different browsers and devices.

87. What is the difference between a stateful component and a stateless


component in React?

In React, a stateful component, also known as a “smart” or “container”


component, is a component that maintains its own internal state, typically via
the useState or this.state hooks. It may also manage data that is passed down to
it as props from other components, and it may use lifecycle methods, such as
componentDidMount, to fetch data or perform other side effects.

On the other hand, a stateless component, also known as a “dumb” or


“presentational” component, is a component that only receives data via props
and does not maintain its own internal state. It simply renders the data it
receives in a visually appealing way and does not manage or manipulate it in any
way. These components are considered “pure” because they are only concerned
with the rendering of the data and do not have side effects.

The key difference between the two is the way they manage and manipulate
data. Stateful components have their own internal state and are responsible for
managing and updating it, whereas stateless components simply receive data
via props and render it without any data manipulation.

88. Explain the concept of a Thunk in Redux.

A Thunk in Redux is a function that returns another function instead of a plain


action object. It’s used to perform asynchronous operations and dispatch
multiple actions. Thunks allow you to write action creators that return a function
instead of an action. This can be useful for performing asynchronous operations,
such as API calls, and dispatching multiple actions, such as one to indicate that
the API call has started and another to indicate that it has finished. The inner
function receives the store’s dispatch method as an argument, which can be
used to dispatch actions at any point in the future. Thunks are typically
implemented using a middleware, such as the redux-thunk middleware.

89. How do you handle security in a React application?

Handling security in a React application involves multiple steps, including:

Input validation: Validate all user inputs on the client and server side to prevent
any malicious data from being processed.

Authenticating and authorizing users: Use a secure authentication mechanism


such as JSON Web Tokens (JWT) to ensure that only authorized users can access
sensitive data.

Storing sensitive data securely: Do not store sensitive information such as


passwords and credit card numbers in local storage, use encrypted storage
instead.

Implementing HTTPS: Use HTTPS to ensure secure communication between the


client and server and protect against network attacks such as man-in-the-middle
attacks.

Keeping dependencies up-to-date: Regularly update React and its dependencies


to patch any known security vulnerabilities.
Using Content Security Policy (CSP): Implement a Content Security Policy (CSP) to
restrict the types of resources that can be loaded in a React application and
prevent cross-site scripting (XSS) attacks.

Regular security audits: Conduct regular security audits to identify and address
potential security issues in a timely manner.

90. What is the difference between a function component and a class


component in React?

In React, there are two main types of components: function components and
class components.

Function Components, also known as “stateless” or “functional” components, are


JavaScript functions that accept props as input and return React elements as
output. They are simple, easy to understand and test, and are usually used for
presentational components that don’t have their own state or lifecycle methods.

Class Components, on the other hand, are JavaScript classes that extend the
React.Component base class. They are used for creating components that have a
state, or need to access lifecycle methods such as componentDidMount or
shouldComponentUpdate. Class components are more complex than function
components, but provide more advanced features.

In summary, the main difference between function and class components in


React is that function components are simpler, more straightforward, and easier
to understand, while class components are more powerful and provide more
advanced features, but are also more complex.

91. Explain the concept of a Provider in React-Redux.

The “Provider” in React-Redux is a higher-order component that wraps your


React application and provides it with the ability to access the Redux store. It
allows you to pass the store down to your components using context, without
having to manually pass it down as props through every level of the component
tree.

By using the Provider, you ensure that all of your components can subscribe to
the store and dispatch actions to modify its state. In other words, the Provider
acts as a bridge between your React components and your Redux store, making
the store accessible to all components in your application.

92. How do you handle code splitting in a React application?

Code splitting in React can be handled using the following approaches:


Dynamic Imports: Dynamic imports allow you to load a component lazily only
when it is needed. This is done using the import() syntax and provides a way to
split code into smaller chunks that can be loaded on demand.
1 import React, { Suspense } from
'react’;
2
const LazyComponent = React.lazy(()
3
=> import('./LazyComponent'));
4
function App() {
5
return (
6
<div>
7
<Suspense
8 fallback={<div>Loading...</div>}>
9 <LazyComponent />
10 </Suspense>

11 </div>
);
}

1 import React, { lazy, Suspense }


from 'react’;
2
import { Route } from 'react-
3
router-dom’;
4
const Home = lazy(() =>
5 import('./Home'));

6 const About = lazy(() =>


import('./About'));
7
function App() {
8
return (
9
<div>
10
<Suspense
11 fallback={<div>Loading...</div>}>

12 <Route exact path="/"


13 component={Home} />

14 <Route path="/about"
component={About} />
</Suspense>
</div>

);
}

Webpack Bundle Analyzer: This is a tool that provides a visual representation of


the code and its size. You can use this tool to identify the large chunks of code
that can be split into smaller chunks and loaded lazily.

By using these approaches, you can effectively handle code splitting in a React
application and improve its performance by reducing the initial loading time and
only loading the required code on demand.

93. What is the difference between a connected component and a


component in React-Redux?

Connected Component (Higher Order


Component
Component)
A plain React component that receives
Definition props and returns a tree of React
elements.
Used to display UI elements, manage
Usage local component state and pass props
to child components.
Example A button, a form, a card, etc.
Connected components are higher-order components that are wrapped around
plain components to provide them access to the Redux store. Connected
components are used to access the state of the store and dispatch actions,
whereas plain components are used to manage UI elements and local
component state.

94. Explain the concept of a Sagas in Redux.

A Saga in Redux is a way to manage side effects (e.g. asynchronous operations


like data fetching and impure operations like accessing the browser cache) in a
Redux application. It is implemented as a middleware using generator functions
in JavaScript and runs in the background, separate from the main thread of your
application, watching for actions dispatched to the store. When a specific action
is detected, the Saga can perform various tasks and trigger additional actions as
needed, updating the store based on the results of the asynchronous
operations. The key benefit of using Sagas is that they make it easier to reason
about, test, and manage the flow of data in your application.
95. How do you handle code optimization in a large React application?

Handling code optimization in a large React application can be achieved through


several approaches:

50. Code splitting: This allows you to split your code into smaller chunks that
can be loaded on demand, reducing the initial load time of your
application.
51. Lazy loading: Lazy loading allows you to load components only when they
are required, reducing the amount of code that needs to be loaded and
parsed at startup.
52. Use of a bundler such as Webpack: A bundler can help you optimize your
code by reducing the size of your JavaScript files, combining multiple files
into one, and more.
53. Use of caching: You can cache the data and components that are
frequently used in your application to avoid fetching the same data over
and over.
54. Use of efficient algorithms and data structures: In order to keep your
application fast, it’s important to use algorithms and data structures that
are optimized for performance.
55. Regular performance monitoring and profiling: Regular performance
monitoring and profiling can help you identify performance bottlenecks
and areas for improvement in your code.
56. Use of optimization techniques such as memoization: By using techniques
such as memoization, you can reduce the number of unnecessary re-
renders and computations in your application, improving its overall
performance.

96. What is the difference between a React component and a React


element?

A React component is a JavaScript class or function that returns a React element.


It is a reusable piece of UI that describes a part of the user interface.

A React element, on the other hand, is a plain JavaScript object that represents a
DOM node. It is an immutable representation of a DOM node, which can be
created using React.createElement or JSX.

In short, a component is a blueprint for creating elements, and an element is an


instance of a component.

97. Explain the concept of a Middleware in Redux.


In Redux, a middleware is a software component that sits between the store and
the action dispatching process to add additional functionality, such as logging,
crash reporting, handling asynchronous actions, etc. It allows you to extend the
store’s behavior without modifying the store itself. Middlewares are applied
using the applyMiddleware method and can be composed together to achieve a
desired behavior. When an action is dispatched, it passes through each
middleware in the order they were composed, giving the middleware an
opportunity to interact with the action before it reaches the store. This provides
a way to manipulate actions and state, and to perform complex actions that can
span multiple actions.

98. How do you handle internationalization in a React application?

Handling internationalization (i18n) in a React application involves adapting the


user interface and content of the application to meet the language and cultural
requirements of different locales.

There are several libraries and techniques that can be used to implement
internationalization in a React application, including:

57. react-intl: A popular library for internationalizing React applications. It


provides components for formatting dates, numbers, and strings, as well
as handling pluralization and message extraction.
58. Context API: React’s Context API can be used to store the current locale
and make it available to the components that need it. The locale can be
changed dynamically to switch the language of the application.
59. Custom hooks: Custom hooks can be written to encapsulate the logic for
formatting and retrieving messages, and to make it easier to use in
components.

Here’s an example of how the react-intl library can be used to implement


internationalization in a React application:
1 import React from 'react';

2
3 import { FormattedMessage, useIntl
} from ‘react-intl';
4
function MyComponent() {
5
const intl = useintl();
6
return (
7
<div>
8
<p>
9
<FormattedMessage id="greeting"
10
defaultMessage="Hello, World!" />
11
</p>
12
<p>
13
{int1.formatDate(new Date(), {
14
weekday: 'long’,
15
year: ‘numeric’,
16
month: 'long’,
17
day: ‘numeric’,
18
})}
19
</p>
20
</div>
);

In this example, the useIntl hook is used to access the intl object, which provides
internationalization functions like formatDate. The FormattedMessage
component is used to display a localized message with the ID greeting.

Implementing internationalization in a React application can greatly improve the


user experience for users who speak different languages and are located in
different regions. It’s an important consideration for any application that aims to
have a global reach.

99. What is the difference between a React component and a React class?

When it comes to an interview, it’s important to understand the difference


between React class components and functional components. This knowledge
can demonstrate your understanding of React and its components, and it may
also show your ability to write efficient and maintainable code.

When asked about class components, you can highlight that they are defined as
JavaScript classes that extend the React.Component class, have a render
method, and can have additional lifecycle methods and state. You can also
provide a simple example to show your understanding of class components.

When asked about functional components, you can emphasize that they are
defined as plain JavaScript functions that return the component’s JSX markup,
and that they can use state and other React features with hooks. You can also
give an example to show how to write a functional component that achieves the
same functionality as a class component.

Finally, you can explain the trade-offs between class components and functional
components, such as that functional components are generally simpler and
easier to read, while class components offer more features and flexibility.
Showing your ability to weigh the pros and cons of each approach can
demonstrate your critical thinking skills and ability to write maintainable code.

100. Explain the concept of a Memoization in React.

In React, memoization is a technique used to optimize the performance of a


component by avoiding unnecessary re-renders. It involves caching the results
of a component’s render so that if the inputs (props) to the component do not
change, the cached result can be reused, instead of re-computing the result.

React provides a built-in hook called useMemo for implementing memoization.


useMemo takes a function and an array of dependencies as arguments and
returns a memoized value. The function is re-executed only if one or more of the
dependencies have changed.

Here is an example of how useMemo can be used to memoize an expensive


calculation:
1 import React, { useMemo } from
'react’;
2
function MyComponent({ data }) {
3
const memoizedvalue = useMemo(() =>
4
{
5
// Do some expensive calculation
6
7 let result = 0;

8 for (let i = 0; i < data.length;


i++) {
9
result += data[i];
10
}
11
return result;
12
}, [data]);
return <div>The result is
{memoizedvalue}</div>;
}

In this example, useMemo is used to memoize the result of the expensive


calculation performed on data. The calculation will only be re-executed if the
value of data changes.

Memoization can greatly improve the performance of a React application by


avoiding unnecessary re-renders and re-calculations, especially when dealing
with complex or large data structures.

101. How do you handle events in React?

When building a React application, it’s common to need to respond to user


actions such as button clicks, form submissions, and other events. In React, this
is achieved through the use of event handlers. An event handler is a callback
function that is attached to an element in the UI, and it’s executed when a
specified event occurs.

For example, to handle a click event on a button, you would define a function in
your React component that updates the component’s state, and then attach that
function to the button as an onClick event handler.
1 class MyComponent extends
React.Component {
2
constructor(props) {
3
super(props);
4
this.state = {count: 0};
5
}
6
handleclick() {
7
8 this.setstate({count:
this.state.count + 1});
9
}
10
render() {
11
return (
12
<div>
13
<p>You clicked {this.state.count}
14
times</p>
15
<button onClick={() =>
16 this.handleClick()}>
17 Click me

18 </button>
</div>

);
}

In this example, when the button is clicked, the handleClick function is called and
the component’s state is updated. This causes a re-render of the component,
and the displayed count is updated accordingly.

Event handlers are a key part of React’s event handling system and are used to
add interactivity to your application.

Group_WPF _MVVVM

Group_VCPlusPlus_MFC
1. What are the different data types present in C++?
The 4 data types in C++ are given below:
i. Primitive Datatype (basic datatype). Example- char, short, int, float, long, double,
bool, etc.
ii. Derived datatype. Example- array, pointer, etc.
iii. Enumeration. Example- enum
iv. User-defined data types. Example- structure, class, etc.
2. What is the difference between C and C++?
The main difference between C and C++ are provided in the table below:

C C++
C is a procedure-oriented programming C++ is an object-oriented programming
language. language.
Data is hidden by encapsulation to ensure that
C does not support data hiding. data structures and operators are used as
intended.
C is a subset of C++ C++ is a superset of C.
Function and operator overloading are not Function and operator overloading is
supported in C supported in C++
Namespace is used by C++, which avoids
Namespace features are not present in C
name collisions.
Functions can not be defined inside structures. Functions can be defined inside structures.
calloc() and malloc() functions are used for new operator is used for memory allocation
memory allocation and free() function is used and deletes operator is used for memory
for memory deallocation. deallocation.
3. What are class and object in C++?
A class is a user-defined data type that has data members and member functions. Data members
are the data variables and member functions are the functions that are used to perform
operations on these variables.
An object is an instance of a class. Since a class is a user-defined data type so an object can
also be called a variable of that data type.
A class is defined as-
class A{
private:
int data;
public:
void fun(){

}
};
4. What is operator overloading?
Operator Overloading is a very essential element to perform the operations on user-defined
data types. By operator overloading we can modify the default meaning to the operators like +,
-, *, /, <=, etc.
For example -
The following code is for adding two complex number using operator overloading-
class complex{
private:
float r, i;
public:
complex(float r, float i){
this->r=r;
this->i=i;
}
complex(){}
void displaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
return complex(r+c.r, i+c.i);
}
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}
5. What is polymorphism in C++?
Polymorphism in simple means having many forms. Its behavior is different in different
situations. And this occurs when we have multiple classes that are related to each other by
inheritance.
For example, think of a base class called a car that has a method called car brand(). Derived
classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation
of a cars
The two types of polymorphism are:
i. Compile Time Polymorphism
ii. Runtime Polymorphism
6. Explain constructor?
The constructor is a member function that is executed automatically whenever an object is
created. Constructors have the same name as the class of which they are members so that
compiler knows that the member function is a constructor. And no return type is used for
constructors.
Example:
class A{
private:
int val;
public:
A(int x){ //one argument constructor
val=x;
}
A(){ //zero argument constructor
}
}
int main(){
A a(3);

return 0;
}
7. What is a virtual function?
Virtual function is a member function in the base class that you redefine in a derived class. A
virtual function is declared using the virtual keyword. When the function is made virtual, C++
determines which function is to be invoked at the runtime based on the type of the object
pointed by the base class pointer.
8. Compare compile time polymorphism and Runtime polymorphism.
The main difference between compile-time and runtime polymorphism is provided below:

Compile-time polymorphism Run time polymorphism


In this method, we would come to know at In this method, we come to know at run time
compile time which method will be called. which method will be called. The call is not
And the call is resolved by the compiler. resolved by the compiler.
It provides slow execution compared to
It provides fast execution because it is known
compile-time polymorphism because it is
at the compile time.
known at the run time.
It is achieved by function overloading and It can be achieved by virtual functions and
operator overloading. pointers.
Example -
Example -
class A{
int add(int a, int b){ public:
return a+b; virtual void fun(){
} cout<<"base ";
int add(int a, int b, int c){ }
return a+b+c; };
} class B: public A{
public:
int main(){ void fun(){
cout<<add(2,3)<<endl; cout<<"derived ";
cout<<add(2,3,4)<<endl; }
};
int main(){
return 0; A *a=new B;
} a->fun();
return 0;
}
9. What do you know about friend class and friend function?
A friend class can access private, protected, and public members of other classes in which it is
declared as friends.
Like friend class, friend function can also access private, protected, and public members. But,
Friend functions are not member functions.
For example -
class A{
private:
int data_a;
public:
A(int x){
data_a=x;
}
friend int fun(A, B);
}
class B{
private:
int data_b;
public:
A(int x){
data_b=x;
}
friend int fun(A, B);
}
int fun(A a, B b){
return a.data_a+b.data_b;
}
int main(){
A a(10);
B b(20);
cout<<fun(a,b)<<endl;
return 0;
}
Here we can access the private data of class A and class B.
10. What are the C++ access specifiers?
In C++ there are the following access specifiers:
i. Public: All data members and member functions are accessible outside the class.
ii. Protected: All data members and member functions are accessible inside the class
and to the derived class.
iii. Private: All data members and member functions are not accessible outside the class.

11. Define inline function.


If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time. One of the important advantages of using an inline
function is that it eliminates the function calling overhead of a traditional function.
12. What is a reference in C++?
A reference is like a pointer. It is another name of an already existing variable. Once a reference
name is initialized with a variable, that variable can be accessed by the variable name or
reference name both.
For example-
int x=10;
int &ref=x; //reference variable
If we change the value of ref it will be reflected in x. Once a reference variable is initialized it
cannot refer to any other variable. We can declare an array of pointers but an array of references
is not possible.
13. What do you mean by abstraction in C++?
Abstraction is the process of showing the essential details to the user and hiding the details
which we don’t want to show to the user or hiding the details which are irrelevant to a particular
user.
14. Is destructor overloading possible? If yes then explain and if no then why?
No destructor overloading is not possible. Destructors take no arguments, so there’s only one
way to destroy an object. That’s the reason destructor overloading is not possible.
15. What do you mean by call by value and call by reference?
In call by value method, we pass a copy of the parameter is passed to the functions. For these
copied values a new memory is assigned and changes made to these values do not reflect the
variable in the main function.
In call by reference method, we pass the address of the variable and the address is used to
access the actual argument used in the function call. So changes made in the parameter alter
the passing argument.
16. What is an abstract class and when do you use it?
A class is called an abstract class whose objects can never be created. Such a class exists as a
parent for the derived classes. We can make a class abstract by placing a pure virtual function
in the class.
17. What are destructors in C++?
A constructor is automatically called when an object is first created. Similarly when an object
is destroyed a function called destructor automatically gets called. A destructor has the same
name as the constructor (which is the same as the class name) but is preceded by a tilde.
Example:
class A{
private:
int val;
public:
A(int x){
val=x;
}
A(){
}
~A(){ //destructor
}
}
int main(){
A a(3);
return 0;
}
18. What are the static members and static member functions?
When a variable in a class is declared static, space for it is allocated for the lifetime of the
program. No matter how many objects of that class have been created, there is only one copy
of the static member. So same static member can be accessed by all the objects of that class.
A static member function can be called even if no objects of the class exist and the static
function are accessed using only the class name and the scope resolution operator ::
19. Explain inheritance.
Inheritance is the process of creating new classes, called derived classes, from existing classes.
These existing classes are called base classes. The derived classes inherit all the capabilities of
the base class but can add new features and refinements of their own.
Example-
Inheritance in C++
Class Bus, Class Car, and Class Truck inherit the properties of Class Vehicle.
The most important thing about inheritance is that it permits code reusability.

=================================================================
===
20. What is a copy constructor?
A copy constructor is a member function that initializes an object using another object of the
same class.
Example-
class A{
int x,y;
A(int x, int y){
this->x=x;
this->y=y;
}

};
int main(){
A a1(2,3);
A a2 = a1; //default copy constructor is called
return 0;
}
We can define our copy constructor. If we don’t define a copy constructor then the default
copy constructor is called.
21. What is the difference between shallow copy and deep copy?
The difference between shallow copy and a deep copy is given below:
Shallow Copy Deep Copy
Deep copy makes a new and separate copy of
Shallow copy stores the references of objects
an entire object with its unique memory
to the original memory address.
address.
Shallow copy is faster. Deep copy is comparatively slower.
Shallow copy reflects changes made to the Deep copy doesn’t reflect changes made to
new/copied object in the original object. the new/copied object in the original object
22. What is the difference between virtual functions and pure virtual functions?
A virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the virtual keyword.
Example-
class base{
public:
virtual void fun(){

}
};
A pure virtual function is a function that has no implementation and is declared by assigning
0. It has no body.
Example-
class base{
public:
virtual void fun()=0;
};
Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything.
It is used to simply tell the compiler that a function will be pure and it will not have anybody.
23. If class D is derived from a base class B. When creating an object of type D in
what order would the constructors of these classes get called?
The derived class has two parts, a base part, and a derived part. When C++ constructs derived
objects, it does so in phases. First, the most-base class (at the top of the inheritance tree) is
constructed. Then each child class is constructed in order until the most-child class is
constructed last.
So the first Constructor of class B will be called and then the constructor of class D will be
called.
During the destruction exactly reverse order is followed. That is destructor starts at the most-
derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be called.
24. Can we call a virtual function from a constructor?
Yes, we can call a virtual function from a constructor. But the behavior is a little different in
this case. When a virtual function is called, the virtual call is resolved at runtime. It is always
the member function of the current class that gets called. That is the virtual machine doesn’t
work within the constructor.
For example-
class base{
private:
int value;
public:
base(int x){
value=x;
}
virtual void fun(){

}
}

class derived{
private:
int a;
public:
derived(int x, int y):base(x){
base *b;
b=this;
b->fun(); //calls derived::fun()
}
void fun(){
cout<<”fun inside derived class”<<endl;
}
}
25. What are void pointers?
A void pointer is a pointer which is having no datatype associated with it. It can hold addresses
of any type.
For example-
void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch
We can assign a pointer of any type to a void pointer but the reverse is not true unless you
typecast it as
str=(char*) ptr;
26. What is this pointer in C++?
The member functions of every object have a pointer named this, which points to the object
itself. The value of this is set to the address of the object for which it is called. It can be used
to access the data in the object it points to.
Example
class A{
private:
int value;
public:
void setvalue(int x){
this->value=x;
}
};

int main(){
A a;
a.setvalue(5);
return 0;
}
27. How do you allocate and deallocate memory in C++?
The new operator is used for memory allocation and deletes operator is used for memory
deallocation in C++.
For example-
int value=new int; //allocates memory for storing 1 integer
delete value; // deallocates memory taken by
value

int *arr=new int[10]; //allocates memory for storing 10 int


delete []arr; // deallocates memory occupied by arr

28. What is a friend function?


You can define a friend function as a function that can access private, public and protect
members of the class. You declare the friend function with the help of the friend keyword. You
declare this function inside the class.
29. What is STL?
STL stands for standard template library. It is a library of container templates that provide
generic classes and functions.
STL components are containers, algorithms, iterators, and function objects.

=================================================================
=

30. How are virtual functions different from pure virtual functions?
A virtual function is a base class member function that a derived class can modify. A member
function of a base class that is a pure virtual function must be defined in the derived type;
otherwise, the derived class will become abstract as well.
31. How would you deallocate and allocate memory in C++?
The heap is used in C to allocate dynamic memory, and these functions are part of the standard
library. malloc() and free are the two important dynamic memory operations (). The size of the
desired memory area in bytes is the only parameter accepted by the malloc() function.
#include <iostream>

#include <cstdlib>

#include <cstring>

using namespace std;

int main() {

char *user;

user = (char *) malloc(25);

strcpy(user, "Pramod Gupta");

cout << "User Name = " << user << " " << &user << endl;

free(user);

32. What is containership?


You can contain an object of one class into another, and that object will be a member of the
other class. This relationship between classes wherein one class contains the object of another
class is referred to as containership.

33. What is data hiding?


The process of hiding elements of a program's code from object members is called data hiding.
It ensures controlled data access and objects integrity. It also prevents unintentional or intended
changes to the program.
34. What is the use of getline in C++?
The C++ getline() is a standard library in-built function and it is defined in the <string.h>
header file. It allows accepting and reading single and multiple lines.
35. What operators cannot be overloaded?
The following operators cannot be overloaded:

• ?: – conditional operator
• .* – dereferencing operator
• sizeof – sizeof operator
• :: – scope resolution operator
• . – Dot operator
• -> – member dereferencing operator
36. What do you understand about smart pointers in C++?
Smart pointers are employed in garbage collection to ensure no memory leaks. If you use smart
pointers, you need not call delete for any memory allocated dynamically as it is automatically
deallocated. You can implement smart pointers in C++11 and higher versions. C++11 has the
following four kinds of smart pointers:
• auto_ptr
• unique_ptr
• shared_ptr
• weak_ptr.
37. What is the role of this pointer and void pointer?
This pointer: The 'this pointer' is present in the member functions of every object. It points to
the object itself and can be used to access the object's data.
Void pointer: A pointer that has no data type associated with it is called a void pointer. You
can assign any type of pointer to a void pointer, but the reverse isn't true unless you use it as
follows
Void *ptr;

String str=(char*) ptr;.

38. What do you understand about pure virtual functions?


A virtual function is a member function in the base class that can be redefined in a derived
class. It can be declared using the virtual keyword. On the contrary, a pure virtual function has
no implementation. It has no body and is declared by assigning 0.
39. Is it possible to call a virtual function from a constructor?
Yes, you can call a virtual function from a constructor. However, the behavior differs in that
case. When you call a virtual function, the virtual call is resolved at runtime. The virtual
machine does not work within the constructor.
40. Define ‘std’?
‘std’ is also known as Standard or it can be interpreted as a namespace. The command “using
namespace std” informs the compiler to add everything under the std namespace and inculcate
them in the global namespace. This all inculcation of global namespace benefits us to use
“cout” and “cin” without using “std::_operator_”.

41. What are references in C++?


When a variable is described as a reference it becomes an alias of the already existing variable.
In simple terms, a referenced variable is another named variable of an existing variable keeping
in mind that changes made in the reference variable will be reflected in the already existing
variable. A reference variable is preceded with a ‘&’ symbol.
Syntax:
int GFG = 10;

// reference variable
int& ref = GFG;

42. Compare Call by Value and Call by Reference?


In C++ programming language to call a function we have 2 methods: Call by Value and Call
by Reference

Call by Value Call by Reference

A copy of a variable is passed. A variable itself is passed fundamentally.

Calling a function by sending the values by Calling a function by sending the address
copying variables. of the passed variable.

The changes made in the function are never The changes made in the functions can be
reflected outside the function on the seen outside the function on the passed
variable. In short, the original value is function. In short, the original value is
never altered in Call by Value. altered in Call by reference.
Passed actual and formal parameters are Passed actual and formal parameters are
stored in different memory locations. stored in the same memory location.
Therefore, making Call by Value a little Therefore, making Call by Reference a
memory insufficient little more memory efficient.

43. Compare struct and class?

Struct Class

Members of the struct are always by Members of the class can be in private,
default public mode protected, and public modes.

Classes do support the concept of


Structure does not support inheritance. inheritance.

Structures are of the value type. They only Classes are of reference type. It holds a
hold value in memory. reference of an object in memory.

The memory in structures is stored as


stacks The memory in classes is stored as heaps.

44. What is the difference between reference and pointer?

Reference Pointer

The value of a reference cannot be


reassigned The value of a pointer can be reassigned

It can never hold a null value as it needs an It can hold or point at a null value and be
existing value to become an alias of termed as a nullptr or null pointer

It cannot work with arrays It can work with arrays

To access the members of class/struct it To access the members of class/struct it


uses a ‘ . ‘ uses a ‘ -> ‘
The memory location of a pointer cannot
The memory location of reference can be be accessed easily as we have to use a
accessed easily or it can be used directly dereference ‘ * ‘

45. What is the difference between function overloading and operator overloading?

Function Overloading Operator Overloading

It is basically defining a function in It is basically giving practice of giving a


numerous ways such that there are many special meaning to the existing meaning of
ways to call it or in simple terms you have an operator or in simple terms redefining
multiple versions of the same function the pre-redefined meaning

Parameterized Functions are a good


example of Function Overloading as just Polymorphism is a good example of an
by changing the argument or parameter of a operator overloading as an object of
function you make it useful for different allocations class can be used and called by
purposes different classes for different purposes

Example of Function Overloading: Example of Operator Overloading:


1. int GFG(int X, int Y); 1. int GFG() = X() + Y();
2. int GFG(char X, char Y); 2. int GFG() = X() – Y();

46. What is the difference between an array and a list?

Arrays Lists

Lists are classic individual elements that


Array are contiguous memory locations of are linked or connected to each other with
homogenous data types stored in a fixed the help of pointers and do not have a fixed
location or size. size.

Arrays are static in nature. Lists are dynamic in nature

Uses more memory as it has to store the


Uses less memory than linked lists. value and the pointer memory location
47. What is the difference between a while loop and a do-while loop?

While Loop do-while Loop

While loop is also termed an entry- The do-while loop is termed an exit control
controlled loop loop

Even if the condition is not satisfied the


If the condition is not satisfied the statements inside the loop will execute for
statements inside the loop will not execute at least one time

Example of a do-while loop:


do {
Example of a while loop:
while(condition) statements to be executed;
{statements to be executed;}; } while(condition or expression);

48. Discuss the difference between prefix increment/decrement and postfix


increment/decrement?

prefix postfix

It simply means putting the operator before It simply means putting the operator after
the operand the operand

It executes itself before ‘; ‘ It executes itself after ‘; ‘

Associativity of prefix ++ is right to left Associativity of postfix ++ is left to right

49. What is the difference between new and malloc()?

new malloc()

new is an operator which performs an malloc is a function that returns and


operation accepts values

new calls the constructors malloc cannot call a constructor


new is faster than malloc as it is an
operator malloc is slower than new as it is a function

new returns the exact data type malloc returns void*

50. What is the difference between virtual functions and pure virtual functions?

Virtual Function Pure Virtual Function

A Pure Virtual Function is a member


function of a base class that is only
A Virtual Function is a member function of declared in a base class and defined in a
a base class that can be redefined in derived class to prevent it from becoming
another derived class. an abstract class.

There is no definition in Pure Virtual


A virtual Function has its definition in its Function and is initialized with a pure
respective base class. specifier (= 0).

A base class having pure virtual function


The base class has a virtual function that becomes abstract that cannot be
can be represented or instanced; In simple represented or instanced; In simple words,
words, its object can be made. it means its object cannot be made.

51. Compare compile-time polymorphism and Runtime polymorphism.

Compile-Time Polymorphism Runtime Polymorphism

It is also termed static binding and early It is also termed Dynamic binding and Late
binding. binding.

It is fast because execution is known early It is slow as compared to compile-time


at compile time. because execution is known at runtime.
It is achieved by function overloading and It is achieved by virtual functions and
operator overloading. function overriding.

52. How delete [] is different from delete?

delete[] delete

It is used for deleting a whole array It is used to delete only one single pointer

It is used for deleting the objects of new[]; It is used for deleting the objects of new;
By this, we can say that delete[] is used to By this, we can say that delete is used to
delete an array of objects delete a single object

It can only call the destructor of a class


It can call as many destructors it wants once

53. When should we use multiple inheritance?


Multiple inheritances mean that a derived class can inherit two or more base/parent classes. It
is useful when a derived class needs to combine numerous attributes/contracts and inherit some,
or all, of the implementation from these attributes/contracts. To take a real-life example
consider your Parents where Parent A is your DAD Parent B is your MOM and Chid C is you.

Multiple Inheritances

54. How to resolve the ambiguity in multiple inheritance? OR What is virtual


inheritance?
Virtual inheritance is a technique that ensures only one copy of a base class’s member variables
is inherited by grandchild-derived classes. Or in simple terms, virtual inheritance is used when
we are dealing with a situation of multiple inheritances but want to prevent multiple instances
of the same class from appearing in the inheritance hierarchy.
55. What is a virtual destructor?
When destroying instances or objects of a derived class using a base class pointer object, a
virtual destructor is invoked to free up memory space allocated by the derived class object or
instance.
Virtual destructor guarantees that first the derived class’ destructor is called. Then the base
class’s destructor is called to release the space occupied by both destructors in the inheritance
class which saves us from the memory leak. It is advised to make your destructor virtual
whenever your class is polymorphic.
56. Is destructor overloading possible? If yes then explain and if no then why?
The simple answer is NO we cannot overload a destructor. It is mandatory to only destructor
per class in C++. Also to mention, Destructor neither take arguments nor they have a parameter
that might help to overload.
57. Which operations are permitted on pointers?
Pointers are the variables that are used to store the address location of another variable.
Operations that are permitted to a pointer are:
1. Increment/Decrement of a Pointer
2. Addition and Subtraction of integer to a pointer
3. Comparison of pointers of the same type

58. What is the purpose of the “delete” operator?


The delete operator is used to delete/remove all the characteristics/properties from an object by
deallocating its memory; furthermore, it returns true or false in the end. In simple terms, it
destroys or deallocates array and non-array(pointer) objects which are created by new
expressions.

int GFG = new int[100];

// uses GFG for


deletion

delete [] GFG;

59. What do you know about friend class and friend function?
A friend class is a class that can access both the protected and private variables of the classes
where it is declared as a friend.
Example of friend class:

class Class_1st {

// ClassB is a friend class of


ClassA

friend class Class_2nd;

statements;
}

class Class_2nd {

statements;

A friend function is a function used to access the private, protected, and public data members
or member functions of other classes. It is declared with a friend keyword. The advantage of a
friend function is that it is not bound to the scope of the class and once it is declared in a class,
furthermore to that, it cannot be called by an object of the class; therefore it can be called by
other functions. Considering all the mentioned points we can say that a friend function is a
global function.
Example of friend function:

class GFG {

statements;

friend dataype
function_Name(arguments);

statements;

OR

class GFG{

statements'
friend int divide(10,5);

statements;

60. What is an Overflow Error?


Overflow Error occurs when the number is too large for the data type to handle. In simple
terms, it is a type of error that is valid for the defined but exceeds used the defined range where
it should coincide/lie.
For example, the range of int data type is –2,147,483,648 to 2,147,483,647 and if we declare a
variable of size 2,247,483,648 it will generate a overflow error.
61. What does the Scope Resolution operator do?
A scope resolution operator is denoted by a ‘::‘ symbol. Just like its name this operator resolves
the barrier of scope in a program. A scope resolution operator is used to reference a member
function or a global variable out of their scope furthermore to which it can also access the
concealed variable or function in a program.
Scope Resolution is used for numerous amounts of tasks:
1. To access a global variable when there is a local variable with the same name
2. To define the function outside the class
3. In case of multiple inheritances
4. For namespace

62. Can you compile a program without the main function?


Yes, it is absolutely possible to compile a program without a main(). For example Use Macros
that defines the main

// C++ program to demonstrate


the

// a program without main()

#include <iostream>

#define fun main


using namespace std;

int fun(void)

cout<<"I Love Programming”;

return 0;

63. What is STL?


STL is known as Standard Template Library, it is a library that provides 4 components like
container, algorithms, and iterators.

64. Define inline function. Can we have a recursive inline function in C++?
An inline function is a form of request not an order to a compiler which results in the inlining
of our function to the main function body. An inline function can become overhead if the
execution time of the function is less than the switching time from the caller function to called
function. To make a function inline use the keyword inline before and define the function
before any calls are made to the function.

Inline Function Explanation

Syntax:
inline data_type function_name()
{
Body;
}
The answer is No; It cannot be recursive.
An inline function cannot be recursive because in the case of an inline function the code is
merely placed into the position from where it is called and does not maintain a piece of
information on the stack which is necessary for recursion.
Plus, if you write an inline keyword in front of a recursive function, the compiler will
automatically ignore it because the inline is only taken as a suggestion by the compiler.
65. What is an abstract class and when do you use it?
An abstract class is a class that is specifically designed to be used as a base class. An abstract
class contains at least one pure virtual function. You declare a pure virtual function by using a
pure specifier(= 0) in the declaration of a virtual member function in the class declaration
You cannot use an abstract class as a parameter type, a function return type, or the type of an
explicit conversion, nor can you declare an object of an abstract class. However, it can be used
to declare pointers and references to an abstract class.
An abstract class is used if you want to provide a common, implemented functionality among
all the implementations of the component. Abstract classes will allow you to partially
implement your class, whereas interfaces would have no implementation for any members
whatsoever. In simple words, Abstract Classes are a good fit if you want to provide
implementation details to your children but don’t want to allow an instance of your class to be
directly instantiated.
66. What are the static data members and static member functions?
The static data member of a class is a normal data member but preceded with a static keyword.
It executes before main() in a program and is initialized to 0 when the first object of the class
is created. It is only visible to a defined class but its scope is of a lifetime.
Syntax:
static Data_Type Data_Member;

The static member function is the member function that is used to access other static data
members or other static member functions. It is also defined with a static keyword. We can
access the static member function using the class name or class objects.
Syntax:
classname::function name(parameter);
67. What is the main use of the keyword “Volatile”?
Just like its name, things can change suddenly and unexpectantly; So it is used to inform the
compiler that the value may change anytime. Also, the volatile keyword prevents the compiler
from performing optimization on the code. It was intended to be used when interfacing with
memory-mapped hardware, signal handlers, and machine code instruction.
68. Define storage class in C++.
Storage class is used to define the features(lifetime and visibility) of a variable or function.
These features usually help in tracing the existence of a variable during the runtime of a
program.
Syntax:
storage_class var_data_type var_name;
Some types of storage classes:

Examples of storage class

69. What is a mutable storage class specifier? How can they be used?
Just like its name, the mutable storage class specifier is used only on a class data member to
make it modifiable even though the member is part of an object declared as const. Static or
const, or reference members cannot use the mutable specifier. When we declare a function as
const, this pointer passed to the function becomes const.
70. Define the Block scope variable.
So the scope of a variable is a region where a variable is accessible. There are two scope
regions, A global and block or local.
A block scope variable is also known as a local scope variable. A variable that is defined inside
a function (like main) or inside a block (like loops and if blocks) is a local variable. It can be
used ONLY inside that particular function/block in which it is declared. a block-scoped
variable will not be available outside the block even if the block is inside a function.
71. What is the function of the keyword “auto”?
The auto keyword may be used to declare a variable with a complex type in a straightforward
fashion. You can use auto to declare a variable if the initialization phrase contains templates,
pointers to functions, references to members, etc. With type inference capabilities, we can
spend less time having to write out things the compiler already knows. As all the types are
deduced in the compiler phase only, the time for compilation increases slightly but it does not
affect the runtime of the program.
72. Define namespace in C++.
Namespaces enable us to organize named items that would otherwise have global scope into
smaller scopes, allowing us to give them namespace scope. This permits program parts to be
organized into distinct logical scopes with names. The namespace provides a place to define or
declare identifiers such as variables, methods, and classes.
Or we could say that A namespace is a declarative zone that gives the identifiers (names of
types, functions, variables, and so on) within it a scope. Namespaces are used to arrange code
into logical categories and to avoid name clashes, which might happen when you have many
libraries in your code base.
73. When is void return type used?
The void keyword, when used as a function return type, indicates that the function does not
return a value. When used as a parameter list for a function, void indicates that the function
takes no parameters. Non-Value Returning functions are also known as void functions. They’re
called “void” since they’re not designed to return anything. True, but only partially. We can’t
return values from void functions, but we can certainly return something. Although void
functions have no return type, they can return values.
74. What is ‘this‘ pointer in C++?
this pointer enables every object to have access to its own address through an essential pointer.
All member functions take this pointer as an implicit argument. this pointer may be used to
refer to the calling object within a member function.
• this pointer is used to pass an object as a parameter to another method.
• Each object gets its own copy of the data member.
• this pointer is used to declare indexers.
75. What is Data binding and Abstraction?
Data Binding: Data binding is the method of constructing a link between both the
application's user interface and the information it shows. If the binding has the correct
parameters and the information provides the appropriate notification, whenever the data has
changed its value, the components that are connected to it instantly adapt to the change.
Data Abstraction: Data abstraction is a process of reducing an enormous amount of
information to a simple representation of the whole. Abstraction is the process of diminishing
something to a set of basic characteristics by eliminating or subtracting characteristics.

76. What is a class template?


A class template specifies how classes are generated based on parameters. Containers are
typically implemented using class templates. A class template is created by providing it with a
set of types as template parameters.

77. What are the methods of exporting a function from a DLL?


There are two approaches:
• By Using the type library in the DLL.
• By Using the DLL instance to get a reference to the function.
78. Explain what is C++ exceptional handling?
The practice of handling runtime faults in C++ is known as exception handling. We handle
exceptions so that the application's usual flow can be preserved even when runtime issues
occur. An exception in C++ is a run-time event or object. The std::exception class is where all
exceptions are derived.
79. Mention what are the types of Member Functions?
The types of member functions are
• Simple functions
• Static functions
• Const functions
• Inline functions
• Friend functions
80. Explain what is multi-threading in C++?
• Multitasking is the capability that allows your computer to execute two or more
programs at the same time. Multithreading is a sophisticated form of multitasking.
• A multithreaded program is made up of two or more components that can run at the
same time. A thread is a component of such a program, and each thread defines a
distinct execution path.
81. What is the difference between virtual functions and pure virtual functions?
A virtual function is a base class member function which may modify in a derived class. The
keyword virtual is used to declare it.
Example:
class base{
public:
virtual void fun(){

}
};
A pure virtual function is one that has no implementation and is declared by setting the value
to 0. It doesn't have a body.

Example:
class base{
public:
virtual void fun()=0;
};
The value 0 is not allocated to anything, and the = sign has no bearing on the assignment. Its
sole purpose is to inform the compiler that a function will be pure and will not contain anyone.
82. What are void pointers?
A void pointer is a pointer that doesn't have a datatype attached to it. It may store any form of
address.
Example:
void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch
We can assign any type of pointer to a void pointer, but we can't do the opposite unless we
typecast it as void.
str=(char*) ptr;
83. How do you allocate and deallocate memory in C++?
In C++, the new operator is used to allocate memory, whereas the deletes operator is used to
deallocate memory.
Example:
int value=new int; //allocates memory for storing 1 integer
delete value; // deallocates memory taken by
value

int *arr=new int[10]; //allocates memory for storing 10 int


delete []arr; // deallocates memory occupied by arr
84. What is a virtual destructor?
In C++, a virtual destructor is used in the base class to allow the derived class object to be
destroyed as well. The tilde operator and the virtual keyword are used before the constructor
to declare a virtual destructor.
85. Define the Local and Global scope of a variable.
Global variables are useful for data that are relatively constant or that must be accessed by
multiple functions in the script, such as a session id. A local variable, on the other hand, has a
limited scope: it only exists within the block in which it was defined. The variable is destroyed
and its values are lost once that block ends.
86. Explain what is upcasting in C++?
Upcasting is the process of transforming a derived-class pointer or reference to a base class.
To look at it another way, one can consider a derived type as though it were its base type by
upcasting it. Public inheritance is always allowed when no explicit type cast is used.

Coding Questions (C++)


1. What will be the output of the following program?
#include<iostream>
using namespace std;
int main(){
int a=1;
cout<<(a++)*(++a)<<endl;
return 0;
}

2. What will be the value of x in the following program?


#include<iostream>
using namespace std;
int main(){
int a=1;
int x=(a++)++;
cout<<x<<endl;
return 0;
}

3. Consider the following C++ program and determine the output.


#include<iostream>
using namespace std;
class A{
public:
virtual void a()=0;
A(){
cout<<"A ";
}
};
class B: public A
{
public:
B(){
cout<<"B ";
}
};

int main(){
A *a=new B();

return 0;
}

Here are a few C++ coding questions for practice:

4. WAP to check if a number is a palindrome or not.


5. WAP to find the factorial of a number.
6. How to find the frequency of a digit in a given number?
7. WAP in C++ to print the first non-repeated character in the given string.
8. WAP in C++ to find duplicate numbers in a given array that contains multiple
duplicates.
9. WAP to print the date in dd/mm/yy format.
10. WAP to print the multiplication of two matrix.
11. WAP using recursion to print the factorial of a number.
12. WAP to search an element(s) in a given array.
Group_Java
Group_WPF

SQL

What is Database?
A database is an organized collection of data, stored and retrieved digitally from
a remote or local computer system. Databases can be vast and complex, and
such databases are developed using fixed design and modeling approaches.

What is RDBMS? How is it different from DBMS?


RDBMS stands for Relational Database Management System. The key
difference here, compared to DBMS, is that RDBMS stores data in the form of a
collection of tables, and relations can be defined between the common fields of
these tables.

What are Tables and Fields?

A table is an organized collection of data stored in the form of rows and


columns. Columns can be categorized as vertical and rows as horizontal. The
columns in a table are called fields while the rows can be referred to as records.

Define different key in Database and explain?

Primary key:
PRIMARY KEY constraint uniquely identifies each row in a table. It must
contain UNIQUE values and has an implicit NOT NULL constraint.

Candidate key: A candidate key is an attribute or set of attributes that can


uniquely identify a tuple.
Super Key: Super key is an attribute set that can uniquely identify a tuple. A
super key is a superset of a candidate key.

Foreign key: Foreign keys are the column of the table used to point to the
primary key of another table.

Alternate key: There may be one or more attributes or a combination of


attributes that uniquely identify each tuple in a relation. These attributes or
combinations of the attributes are called the candidate keys.

Composite key: Whenever a primary key consists of more than one attribute, it
is known as a composite key. This key is also known as Concatenated Key.

Different SQL Commands:

SQL Command are instructions. It is used to communicate with the database. It


is also used to perform specific tasks, functions, and queries of data.

SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.

SQL commands are categorized into 5 categories.

• DDL - Data Definition Language


• DQL - Data Query Language
• DML - Data Manipulation Language
• DCL - Data Control Language
• TCL - Transaction Control Language

Explain different DDL commands in SQL Server.


• Ans. DDL commands include –
• CREATE – Used to create the database or its objects like table, index,
function, views, triggers, etc.
• DROP – Used to delete objects
• ALTER – Used to change database structures
• TRUNCATE – It erases all records from a table, excluding its database
structure
• COMMENT – Used to add comments to the data dictionary
• RENAME – Used to rename a database object
Create New Table and Add Column and Drop Column and Add
Constrains

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
....
);

CREATE TABLE <table name> (


column1 datatype Primary key,
column2 datatype,
column3 datatype,
....
);

CREATE TABLE <table name>


(
column1 datatype Primary key Identity(<SeeValue>,<NextValue>),
column2 datatype,
column3 datatype,
....
);

-- Unique Key
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(<SeeValue>,<NextValue>),
column2 datatype Unique key (<column name>),
column3 datatype,
....
);

-- Foreign key
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(<SeeValue>,<NextValue>),
column2 datatype Foreign key ,
column3 datatype,
....
);

-- Check
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(< Seed Value>,<NextValue>),
column3 datatype CHECK (Column >=value),
....
);

-- Default
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(<Seed Value>,<Next Value>),
column3 datatype DEFAULT value
....
);

-- Add Column in table ALTER TABLE ADD Column Statement Syntax:


ALTER TABLE table_name ADD (Columnname_1 datatype,Columnname_2
datatype, …Columnname_n datatype ....);

--Adding a column after an existing column


ALTER TABLE table_name ADD COLUMN (column_name
column_definition...) AFTER existing_column

-- To ALTER TABLE
ALTER TABLE table_name ALTER COLUMN column_name column_type;

--ALTER TABLE DROP Column Statement Syntax:


ALTER TABLE table_name DROP COLUMN column_name;

-- Different Constraints Type

ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY


KEY (col1, col2);

ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN


KEY (columnname) REFERENCES tablename (columnname);

ALTER TABLE table_name ADD CONSTRAINT colum_nname UNIQUE


(colum_nname);

ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK


(columnname >= value);

ALTER TABLE table_name ADD CONSTRAINT constraint_name


DEFAULT Value FOR columnname;

ALTER TABLE table_name DROP CONSTRAINT constraint_name;

What is a Join? What are the different types of joins in

Joins are used to combine rows from two or more tables, based on a related
column between them.
Types of Joins:
• INNER JOIN − Returns rows when there is a match in both tables.
• LEFT JOIN − Returns all rows from the left table, even if there are no
matches in the right table.
• RIGHT JOIN − Returns all rows from the right table, even if there are no
matches in the left table.
• FULL OUTER JOIN − Returns rows when there is a match in one of the
tables.
• SELF JOIN − Used to join a table to itself as if the table were two tables,
temporarily renaming at least one table in the SQL statement.
• CARTESIAN JOIN (CROSS JOIN) − Returns the Cartesian product of the
sets of records from the two or more joined tables.

Inner Join – it returns the rows if there is at least one match in two tables.

Left Join – returns all the rows from the left table even if there is no match in the
right table.

Syntax:
1 SELECT ColumnList from LeftTable
2 L
3 LEFT join RightTable R
4 ON L.Column=R.Column
Where R.Column is NULL
Right Join – returns all the rows from the right table even if no matches exist in
the left table.

SELECT ColumnList from LeftTable L


RIGHT join RightTable R
ON L.Column=R.Column
Where L.Column is NULL

Self Join : A SQL Self join is a mechanism of joining a table to itself. You would
use a self join when you wanted to create a result set joining records in the table
with some other records from the same table.
Difference between keys and Constraints?

key: A key is a single or combination of multiple fields in a table.


It is used to fetch or retrieve records/data rows from data table according to the
condition/requirement. Keys are also used to create relationships among
different database tables or views.

Constraints:
SQL constraints are used to specify rules for the data in a table. If there is
any violation between the constraint and the data action, the action is aborted.
Constraints can be specified when the table is created (inside the CREATE
TABLE statement) or after the table is created (inside the ALTER TABLE
statement).

Different type of Constraints:

Let’s look at the different types of constraints which are present in SQL:
Constraint Description
Ensures that a column cannot have a
NOT NULL
NULL value.
Provides a default value for a column
DEFAULT
when none is specified.
Ensures that all the values in a
UNIQUE
column are different
Uniquely identifies each row/record
PRIMARY
in a database table
Uniquely identifies a row/record in
FOREIGN
any another database table
The CHECK constraint ensures that
CHECK all values in a column satisfy certain
conditions.
Used to create and retrieve data from
INDEX
the database very quickly.
What is the primary key?

Ans. A primary key constraint uniquely identifies each row/record in a database


table. Primary keys must contain unique values. Null value and duplicate values
are not allowed to be entered in the primary key column. A table can have only
one primary key. It can consist of single or multiple fields.

What is a foreign key?

Ans. A foreign key (often called the referencing key) is used to link two tables
together. It is a column or a combination of columns whose values match a
Primary Key in a different table. It acts as a cross-reference between tables
because it references the primary key of another table and established a link
between them.

What is a unique key?

Ans. A unique key is a set of one or more than one field/column of a table that
uniquely identifies a record in a database table. A primary key is a special kind
of unique key.

Explain the different types of indexes in SQL.

Ans. There are three types of indexes in SQL:


1. Unique Index – It does not allow a field to have duplicate values if the
column is unique indexed.
2. Clustered Index – This index defines the order in which data is
physically stored in a table. It reorders the physical order of the table and
searches based on key values. There can be only one clustered index per
table.
3. Non-Clustered Index – It does not sort the physical order of the table
and maintains a logical order of the data. Each table can have more than
one non-clustered index.

What is Database Relationship?

Ans. A Database Relationship is defined as the connection between two


relational database tables. The primary table has a foreign key that references
the primary key of another table. There are three types of Database Relationship

One-to-one :

It is used to create a relationship between two tables in which a single row of


the first table can only be related to one and only one records of a second table.

One-to-many :

Any single rows of the first table can be related to one or more rows of the
second tables,

Many-to-many:

t is many to many relationships that create a relationship between two tables.


Each record of the first table can relate to any records (or no records) in the
second table. We use junction table in between to join both the table.
CREATE TABLE dbo.city (
city_id int IDENTITY,
city varchar(50) NOT NULL,
country_id int NOT NULL,
CONSTRAINT PK_city PRIMARY KEY CLUSTERED (city_id)
)
ON [PRIMARY]
GO

CREATE TABLE dbo.country (


country_id int IDENTITY,
country varchar(50) NOT NULL,
CONSTRAINT PK_country PRIMARY KEY CLUSTERED (country_id)
)
ON [PRIMARY]
GO

ALTER TABLE dbo.city WITH NOCHECK


ADD FOREIGN KEY (country_id) REFERENCES dbo.country
(country_id)
GO

-- 1 to 1 relation
CREATE TABLE Employee (
ID int PRIMARY KEY,
Name VARCHAR(50)
);

CREATE TABLE Salary (


EmployeeID int UNIQUE NOT NULL,
SalaryAmount int
);
ALTER TABLE Salary ADD CONSTRAINT FK_Salary_Employee
FOREIGN KEY (EmployeeID) REFERENCES Employee (ID);
-- Many to Many
CREATE TABLE films (
film_id INT PRIMARY KEY
,title VARCHAR(50)
);

CREATE TABLE category (


category_id INT PRIMARY KEY
,name VARCHAR(50)
);

CREATE TABLE film_category


(
film_id INT
,category_id INT
, CONSTRAINT film_cat_pk PRIMARY KEY (film_id, category_id)
, CONSTRAINT FK_film FOREIGN KEY (film_id) REFERENCES films
(film_id)
,CONSTRAINT FK_category FOREIGN KEY (category_id)
REFERENCES category (category_id)
;

Query Syntax:

--SELECT <select_criteria>
--[;]
--<select_criteria> ::=
-- [ TOP ( top_expression ) ]
-- [ ALL | DISTINCT ]
-- { * | column_name | expression } [ ,...n ]
-- [ FROM { table_source } [ ,...n ] ]
-- [ WHERE <search_condition> ]
-- [ GROUP BY <group_by_clause> ]
-- [ HAVING <search_condition> ]
-- [ ORDER BY <order_by_expression> ]
-- [ OPTION ( <query_option> [ ,...n ] ) ]

Query order of execution


• FROM and JOIN s. The FROM clause, and subsequent JOIN s are first
executed to determine the total working set of data that is being queried.
...
• WHERE. ...
• GROUP BY. ...
• HAVING. ...
• SELECT. ...
• DISTINCT. ...
• ORDER BY. ...
• Top

What is Auto Increment in SQL?

Ans. Auto Increment allows a unique number to be generated whenever a new


record is created in a table. Generally, it is the PRIMARY KEY field that we
want to be created automatically every time a new record is inserted.

Difference between Count (*) And Count(Column Name)

In Count(*) it counts the no of rows and in case count(Column name)

It ignore the null value then it counts.

Difference between DELETE, DROP and TRUNCATE

Delete : It removes the pointer to that table about particular Tuple then it is
rollback the data. If there are Identity column in a table, then it will start from
the next records it set the next identity value is a table.

Syntax:
DELETE FROM table_name WHERE condition;

Drop: is a Data Definition Language Command (DDL). It is used to drop the


whole table. With the help of the “DROP” command we can drop (delete) the
whole structure in one go i.e. it removes the named elements of the schema.

Truncate: It is used to delete all the rows from the table and free the space
containing the table.

Order By in SQL
SQL Order By is used to sort the data in ascending or descending order. It sorts
the data in ascending order by default. To sort the data in descending order we
use the DESC keyword.

SELECT column1, column2….


FROM table_name
ORDER BY column1 ASC/DESC, column2 ASC/DESC;

GROUP BY:

the GROUP BY clause is used in conjunction with aggregate functions to group


rows based on one or more columns in a table. It allows you to perform
aggregate calculations, such as sum, count, average, etc., on subsets of data
within the grouped rows.

Syntax:
SELECT column1, column2, ..., aggregate_function(column)
FROM table
WHERE conditions
GROUP BY column1, column2, …

When the GROUP BY clause is used, the result set is divided into groups based
on the columns specified.

Having Clause: It is used to further filtrations of records band it is used in case


Group By clause data.

How to find:
l. duplicate records with one field.
li. duplicate records with more than one field.

Ans. Finding duplicate records with one field:

SELECT COUNT(field)

FROM table_name

GROUP BY field

HAVING COUNT(field) > 1


Finding duplicate records with more than one field:

SELECT field1,field2,field3, COUNT(*)

FROM table_name

GROUP BY field1,field2,field3
HAVING COUNT(*) > 1

What is the difference between TRUNCATE and DELETE?

Ans. This is one of the most commonly asked SQL interview questions. The
difference between TRUNCATE and DELETE are:
DELETE TRUNCATE
Delete command is used to delete a Truncate is used to delete all the rows
specified row in a table. from a table.
You can roll back data after using the
You cannot roll back data.
delete statement.
It is a DML command. It is a DDL command.
It is faster.
It is slower than a truncate statement.

What is the difference between:


SELECT * FROM MyTable WHERE MyColumn <> NULL
SELECT * FROM MyTable WHERE MyColumn IS NULL

Ans. The first syntax will not work because NULL means ‘no value’, and you
cannot use scalar value operators. This is why there is a separate IS – a NULL
predicate in SQL.

What is the difference between CHAR and VARCHAR?


Ans. CHAR is a fixed-length character data type, while VARCHAR is a
variable-length character data type.

What is a subquery in SQL? What are the different types of subquery?


Ans. A subquery is a query within another query. When there is a query within
a query, the outer query is called the main query, while the inner query is called
a subquery. There are two types of a subquery:
• Correlated subquery: It obtains values from its outer query before it
executes. When the subquery returns, it passes its results to the outer
query

Sub Query Example:

Select * From TableName Where column_name in (Select <column name>


From table name)

Select * From TableName Where column_name Not in (Select <column name>


From table name)

Corelated Sub Query:

Select * From TableName Where Exists in (Select <column name> From table
name <alias> Where Tablename.FiledName = TableName.FieldName )

Select * From TableName Where column_name Not in (Select <column name>


From table name).

What are the authentication modes in SQL Server?

Ans. SQL Server has two authentication modes –


• Windows Mode – Default. This SQL Server security model is integrated
with Windows
• Mixed Mode – Supports authentication both by Windows and by SQL
Server

What is Normalization in SQL?


Normalization is used to decompose a larger, complex table into simple and
smaller ones. This helps us in removing all the redundant data.
Generally, in a table, we will have a lot of redundant information which is not
required, so it is better to divide this complex table into multiple smaller tables
which contain only unique information.
First normal form:
A relation schema is in 1NF, if and only if:
• All attributes in the relation are atomic(indivisible value)
• And there are no repeating elements or groups of elements.

Second normal form:


A relation is said to be in 2NF, if and only if:
• It is in 1st Normal Form.
• No partial dependency exists between non-key attributes and key
attributes.

Third Normal form:


A relation R is said to be in 3NF if and only if:
• It is in 2NF.
• No transitive dependency exists between non-key attributes and key
attributes through another non-key attribute
SQL : Set 1
1) Which of the following is generally used for performing tasks like creating the structure of
the relations, deleting relation?
a. DML(Data Manipulation Language)
b. Query
c. Relational Schema
d. DDL(Data Definition Language)

Ans: d

2) Which of the following provides the ability to query information from the database and
insert tuples into, delete tuples from, and modify tuples in the database?

a. DML(Data Manipulation Language)


b. DDL(Data Definition Language)
c. Query
d. Relational Schema
Ans: a

3) Query can also be replaced with_______:

SELECT name, course_id FROM instructor, teaches WHERE instructor_ID= teaches_ID;

a. Select name,course_id from teaches,instructor where instructor_id=course_id;


b. Select name, course_id from instructor natural join teaches;
c. Select name, course_id from instructor;
d. Select course_id from instructor join teaches;
Ans : B

4) Which of the following is generally used for performing tasks like creating the structure of
the relations, deleting relation?

a. DML(Data Manipulation Language)


b. Query
c. Relational Schema
d. DDL(Data Definition Language)
Answer: D

5) Which of the following provides the ability to query information from the database
and insert tuples into, delete tuples from, and modify tuples in the database?

a. DML(Data Manipulation Language)


b. DDL(Data Definition Language)
c. Query
d. Relational Schema

Answer : A

6) The given Query can also be replaced with_______:


1. SELECT name, course_id
2. FROM instructor, teaches
3. WHERE instructor_ID= teaches_ID;

a. Select name,course_id from teaches,instructor where instructor_id=course_id;


b. Select name, course_id from instructor natural join teaches;
c. Select name, course_id from instructor;
d. Select course_id from instructor join teaches;
Answer : B

7) Which one of the following given statements possibly contains the error?
a. select * from emp where empid = 10003;
b. select empid from emp where empid = 10006;
c. select empid from emp;
d. select empid where empid = 1009 and Lastname = 'GELLER';
Answer : D

8) Ready the Query carefully:


1. SELECT emp_name
2. FROM department
3. WHERE dept_name LIKE ' _____ Computer Science';

In the above-given Query, which of the following can be placed in the Query's blank portion
to select the "dept_name" that also contains Computer Science as its ending strings?
a. &
b. _
c. %
d. $

Answer : C

9) Rows of a relation are known as the _______.


a. Degree
b. Tuples
c. Entity
d. All of the above
Answer : B

10) Which one of the following is a type of Data Manipulation Command?


a) Create
b) Alter
c) Delete
d) All of the above

Answer : D

11) In case of any shut down during transaction before commit which of the following
statement is done automatically ?
A. View
B. Commit
C. Rollback
Answer C

12) The term "TCL" stands for


a) Ternary Control Language
b) Transmission Control Language
c) Transaction Central Language
d) Transaction Control Language

Answer : D

13) Which one of the following commands is used for removing (or deleting) a relation forms
the SQL database?
a. Delete
b. Drop
c. Remove
d. All of the above
Answer D
14) Which of the following makes the transaction permanent in the database ?
A. View
B. Commit
C. Rollback

Answer B

15) In order to undo the work of transaction after last commit which one
should be used ?
A. View
B. Commit
C. Rollback
Answer C

16) Which of the following deletes all tuples in the instructor relation for those instructors
associated with a department located in the Watson building which is in department relation.

a) DELETE FROM instructor WHERE dept_name IN 'Watson';


b) DELETE FROM department WHERE building='Watson';
c) DELETE FROM instructor WHERE dept_name IN (SELECT dept name FROM
department WHERE building = ’Watson’);

d) None of the mentioned


Answer(C)

17) Which of the following is not a SQL command?


a) Delete
b) Order By
c) Select
d) OrderBy

Answer : A
18) The given Query can be replaced with ____________:

SELECT name
FROM instructor1
WHERE salary <= 100000 AND salary >= 90000;

a) SELECT name
FROM instructor1
WHERE salary BETWEEN 100000 AND 90000

b) SELECT name
FROM instructor|
WHERE salary BETWEEN 90000 AND 100000;

c) SELECT name
FROM instructor!
WHERE salary <= 90000 AND salary>=100000;

Answer C

19) Wrie a query to find out the Total Count and Max Salary and Min Salary.
Emp
EmpID EmpName Salary
100 Paul 2000
200 Greg 4000
300 Ram 600
400 Shyam 6500
500 Ravi 8000

a) 10,10,2000
b) 5, 5, 4000
c) 8, 600, 2000
d) 5, 8000, 600

Answer: D

20) Create table LTable table (EmpID int)


Insert into LTable
Select 1
Union All
Select 1
Union All
Select 1

Create table RTable table (EmpID int)


Insert into RTable
Select 1
Union All
Select 1
Union All
Select 1

Select LTable.EmpID, RTable.EmpID From LTable Inner Join RTable on


LTable.EmpID=RTable.EmpID;
a) 3
b) 6
c) 12
d) 9

Answer : D
21) Create table LTable table (EmpID int)
Insert into LTable
Select 1
Union All
Select 1
Union All
Select 1

Create table RTable table (EmpID int)


Insert into RTable
Select 1
Union All
Select 1
Union All
Select 1

Select LTable.EmpID, RTable.EmpID From LTable left Join RTable on


LTable.EmpID=RTable.EmpID;
a) 3
b) 6
c) 12
d) 9
Answer : D

22) Create table LTable table (EmpID int)


Insert into LTable
Select 1
Union All
Select 1
Union All
Select 1
Create table RTable table (EmpID int)
Insert into RTable
Select 1
Union All
Select 1
Union All
Select 1
Select LTable.EmpID, RTable.EmpID From LTable left Join RTable on
LTable.EmpID=RTable.EmpID;

a) 3
b) 6
c) 12
d) 9

Answer : D

23)
Create table TblL (EmpID int)
Insert into TblL
Select 100
UNION ALL
Select 200
UNION ALL
Select 300

Create table TbRL (EmpID int)


Insert into TbRL
Select 100
UNION ALL
Select 100
UNION ALL
Select 200
UNION ALL
Select 200
UNION ALL
Select 300
UNION ALL
Select 300
Select 'Inner Join',* From @TblL a inner join @TbRL b on a.EmpID= b.EmpID

Select EmpID, 'Intersect' From @TblL


Intersect
Select EmpID, 'Intersect' From @TbRL

a) Equal No of records
b) Not Equal no of records
c) None of the above
Ans b

24) Char is a ______ length data type and varchar is a ____ data type
a) Fixed Length
b) Variable, Fixed
c) Variable, Variable
d) Fixed , Fixed

Answer : B

25) Auto Value is a property of __ data type


a) INT
b) Char
c) Binary
d) Date
Answer: a

Set 2
1. From the following tables, write a SQL query to find the information on each salesperson
of ABC Company. Return name, city, country and state of each salesperson.
Input:
table: salespersons
salesperson_id|first_name|last_name|
--------------|----------|---------|
1|Green |Wright |
2|Jones |Collins |
3|Bryant |Davis |
table: address
address_id|salesperson_id|city |state |country|
----------|--------------|-----------|----------|-------|
1| 2|Los Angeles|California|USA |
2| 3|Denver |Colorado |USA |
3| 4|Atlanta |Georgia |USA |

Output:
first_name|last_name|city |state |
----------|---------|-----------|----------|
Jones |Collins |Los Angeles|California|
Bryant |Davis |Denver |Colorado |
Green |Wright | | |
2. From the following table, write a SQL query to find the third highest sale. Return sale
amount.
Input:
table: salemast
sale_id|employee_id|sale_date |sale_amt|
-------|-----------|----------|--------|
1| 1000|2012-03-08| 4500|
2| 1001|2012-03-09| 5500|
3| 1003|2012-04-10| 3500|
3| 1003|2012-04-10| 2500|
Output:
SecondHighestSale|
-----------------|
4500|
3. From the following table, write a SQL query to find the Nth highest sale. Return sale
amount.
Input:
table: salemast
sale_id|employee_id|sale_date |sale_amt|
-------|-----------|----------|--------|
1| 1000|2012-03-08| 4500|
2| 1001|2012-03-09| 5500|
3| 1003|2012-04-10| 3500|
Output:
getNthHighestSaleAmt(3)|
-----------------------|
3500|
4. From the following table, write a SQL query to find the marks, which appear at least thrice
one after another without interruption. Return the number.
Input:
table: logs
student_id|marks|
----------|-----|
101| 83|
102| 79|
103| 83|
104| 83|
105| 83|
106| 79|
107| 79|
108| 83|
Output:
ConsecutiveNums|
---------------|
83|
5. From the following table, write a SQL query to find all the duplicate emails (no upper case
letters) of the employees. Return email id.
Input:
table: employees
employee_id|employee_name|email_id |
-----------|-------------|-------------|
101|Liam Alton |li.al@abc.com|
102|Josh Day |jo.da@abc.com|
103|Sean Mann |se.ma@abc.com|
104|Evan Blake |ev.bl@abc.com|
105|Toby Scott |jo.da@abc.com|
Output:
email_id |
-------------|
jo.da@abc.com|
6. From the following tables, write a SQL query to find those customers who never ordered
anything. Return customer name.
Input:
table: customers
customer_id|customer_name|
-----------|-------------|
101|Liam |
102|Josh |
103|Sean |
104|Evan |
105|Toby |
table: orders
order_id|customer_id|order_date|order_amount|
--------|-----------|----------|------------|
401| 103|2012-03-08| 4500|
402| 101|2012-09-15| 3650|
403| 102|2012-06-27| 4800|
Output:
Customers|
---------|
Evan |
Toby |
7. From the following table, write a SQL query to remove all the duplicate emails of
employees keeping the unique email with the lowest employee id. Return employee id and
unique emails.
Input:
table: employees
employee_id|employee_name|email_id |
-----------|-------------|-------------|
101|Liam Alton |li.al@abc.com|
102|Josh Day |jo.da@abc.com|
103|Sean Mann |se.ma@abc.com|
104|Evan Blake |ev.bl@abc.com|
105|Toby Scott |jo.da@abc.com|
Output:
employee_id|employee_name|email_id |
-----------|-------------|-------------|
101|Liam Alton |li.al@abc.com|
102|Josh Day |jo.da@abc.com|
103|Sean Mann |se.ma@abc.com|
104|Evan Blake |ev.bl@abc.com|
8. From the following table, write a SQL query to find all dates' city ID with higher pollution
compared to its previous dates (yesterday). Return city ID, date and pollution.
Input:
table: so2_pollution
city_id|date |so2_amt|
-------|----------|-------|
701|2015-10-15| 5|
702|2015-10-16| 7|
703|2015-10-17| 9|
704|2018-10-18| 15|
705|2015-10-19| 14|
Output:
City ID|
-------|
702|
703|
9. A salesperson is a person whose job is to sell products or services.
From the following tables, write a SQL query to find the top 10 salesperson that have made
highest sale. Return their names and total sale amount.
Input:
Table: sales
TRANSACTION_ID|SALESMAN_ID|SALE_AMOUNT|
--------------|-----------|-----------|
501| 18| 5200.00|
502| 50| 5566.00|
503| 38| 8400.00|
...
599| 24| 16745.00|
600| 12| 14900.00|
Table: salesman
SALESMAN_ID|SALESMAN_NAME |
-----------|---------------------|
11|Jonathan Goodwin |
12|Adam Hughes |
13|Mark Davenport |
....
59|Cleveland Hart |
60|Marion Gregory |
Output:
salesman_name |total_sale|
---------------------|----------|
Dan McKee | 70530.00|
Cleveland Klein | 61020.00|
Elliot Clapham | 60519.00|
Evan Blake | 53108.00|
Ollie Wheatley | 52640.00|
Frederick Kelsey | 52270.00|
Sean Mann | 52053.00|
Callum Bing | 48645.00|
Kian Wordsworth | 45250.00|
Bradley Wright | 41961.00|
10. An active customer is simply someone who has bought company's product once before
and has returned to make another purchase within 10 days.
From the following table, write a SQL query to identify the active customers. Show the list of
customer IDs of active customers.
Input:
Table: orders
ORDER_ID|CUSTOMER_ID|ITEM_DESC|ORDER_DATE|
--------|-----------|---------|----------|
101| 2109|juice |2020-03-03|
102| 2139|chocolate|2019-03-18|
103| 2120|juice |2019-03-18|
...
199| 2130|juice |2019-03-16|
200| 2117|cake |2021-03-10|
Output:
customer_id|
-----------|
2103|
2110|
2111|
2112|
2129|
2130|
11. From the following table, write a SQL query to convert negative numbers to positive and
vice verse. Return the number.
Input:
Table name: tablefortest
srno|pos_neg_val|
----|-----------|
1| 56|
2| -74|
3| 15|
4| -51|
5| -9|
6| 32|
Output:
srno|pos_neg_val|converted_signed_value|
----|-----------|----------------------|
1| 56| -56|
2| -74| 74|
3| 15| -15|
4| -51| 51|
5| -9| 9|
6| 32| -32|
12. From the following table, write a SQL query to find the century of a given date. Return
the century.
Input:
Table name: tablefortest
ID|date_of_birth|
--|-------------|
1| 1907-08-15|
2| 1883-06-27|
3| 1900-01-01|
4| 1901-01-01|
5| 2005-09-01|
6| 1775-11-23|
7| 1800-01-01|
Output:
id|date_of_birth|Century|
--|-------------|-------|
1| 1907-08-15| 20 |
2| 1883-06-27| 19 |
3| 1900-01-01| 19 |
4| 1901-01-01| 20 |
5| 2005-09-01| 21 |
6| 1775-11-23| 18 |
7| 1800-01-01| 18 |
13. From the following table, write a SQL query to find the even or odd values. Return
"Even" for even number and "Odd" for odd number.
Input:
Table name: tablefortest
srno|col_val|
----|-------|
1| 56|
2| 74|
3| 15|
4| 51|
5| 9|
6| 32|
Output:
srno|col_val|Even_Odd|
----|-------|--------|
1| 56|Even |
2| 74|Even |
3| 15|Odd |
4| 51|Odd |
5| 9|Odd |
6| 32|Even |
14. From the following table, write a SQL query to find the unique marks. Return the unique
marks.
Input:
Table name: student_test
student_id|marks_achieved|
----------|--------------|
1| 56|
2| 74|
3| 15|
4| 74|
5| 89|
6| 56|
7| 93|
Output:
Unique Marks|
------------|
56|
74|
15|
89|
93|
15. From the following table, write a SQL query to find those students who have referred by
the teacher whose id not equal to 602. Return the student names.
Input:
Table Name: students
student_id|student_name|teacher_id|
----------|------------|----------|
1001|Alex | 601|
1002|Jhon | |
1003|Peter | |
1004|Minto | 604|
1005|Crage | |
1006|Chang | 601|
1007|Philip | 602|
Output:
student_name|
------------|
Alex |
Jhon |
Peter |
Minto |
Crage |
Chang |
16. From the following table, write a SQL query to find the order_id(s) that was executed by
the maximum number of salespersons.
If there are, more than one order_id(s) executed by the maximum number of salespersons
find all the order_id(s). Return order_id.
Input:
Table Name: salemast
salesperson_id|order_id|
--------------|--------|
5001| 1001|
5002| 1002|
5003| 1002|
5004| 1002|
5005| 1003|
5006| 1004|
5007| 1004|
5008| 1004|
Output:
order_id|
--------|
1002|
1004|
17. A city is big if it has an area bigger than 50K square km or a population of more than 15
million.
From the following table, write a SQL query to find big cities name, population and area.
Input:
Table : cities_test
city_name |country |city_population|city_area|
-------------|-------------|---------------|---------|
Tokyo |Japan | 13515271| 2191|
Delhi |India | 16753235| 1484|
Shanghai |China | 24870895| 6341|
Sao Paulo |Brazil | 12252023| 1521|
Mexico City |Mexico | 9209944| 1485|
Cairo |Egypt | 9500000| 3085|
Mumbai |India | 12478447| 603|
Beijing |China | 21893095| 16411|
Osaka |Japan | 2725006| 225|
New York |United States| 8398748| 786|
Buenos Aires |Argentina | 3054300| 203|
Chongqing |China | 32054159| 82403|
Istanbul |Turkey | 15519267| 5196|
Kolkata |India | 4496694| 205|
Manila |Philippines | 1780148| 43|
Output:
city_name |country |city_population|city_area|
------------|--------|---------------|---------|
Delhi |India | 16753235| 1484|
Shanghai |China | 24870895| 6341|
Beijing |China | 21893095| 16411|
Chongqing |China | 32054159| 82403|
Istanbul |Turkey | 15519267| 5196|
18. From the following table, write a SQL query to find those items, which have ordered 5 or
more times. Return item name and number of orders.
Input:
Table: orders
ORDER_ID|CUSTOMER_ID|ITEM_DESC|
--------|-----------|---------|
101| 2109|juice |
102| 2139|chocolate|
103| 2120|juice |
104| 2108|cookies |
105| 2130|juice |
106| 2103|cake |
107| 2122|cookies |
108| 2125|cake |
109| 2139|cake |
110| 2141|cookies |
111| 2116|cake |
112| 2128|cake |
113| 2146|chocolate|
114| 2119|cookies |
115| 2142|cake |
Output:
item_desc|Number of orders|
---------|----------------|
cake | 6|
19. From the following tables, write a SQL query to find the overall rate of execution of
orders, which is the number of orders execution divided by the number of orders quote.
Return rate_of_execution rounded to 2 decimals places.
Input:
Table: orders_issued
distributor_id|company_id|quotation_date|
--------------|----------|--------------|
101| 202| 2019-11-15|
101| 203| 2019-11-15|
101| 204| 2019-11-15|
102| 202| 2019-11-16|
102| 201| 2019-11-15|
103| 203| 2019-11-17|
103| 202| 2019-11-17|
104| 203| 2019-11-18|
104| 204| 2019-11-18|
Table: orders_executed
orders_from|executed_from|executed_date|
-----------|-------------|-------------|
101| 202| 2019-11-17|
101| 203| 2019-11-17|
102| 202| 2019-11-17|
103| 203| 2019-11-18|
103| 202| 2019-11-19|
104| 203| 2019-11-20|
Output:
rate_of_execution|
-----------------|
0.67|
20. From the following table write an SQL query to display the records with four or more
rows with consecutive match_no's, and the crowd attended more than or equal to 50000 for
each match. Return match_no, match_date and audience. Order the result by visit_date,
descending.
Input:
table : match_crowd
match_no|match_date|audience|
--------|----------|--------|
1|2016-06-11| 75113|
2|2016-06-12| 62343|
3|2016-06-13| 43035|
4|2016-06-14| 55408|
5|2016-06-15| 38742|
6|2016-06-16| 63670|
7|2016-06-17| 73648|
8|2016-06-18| 52409|
9|2016-06-19| 67291|
10|2016-06-20| 49752|
11|2016-06-21| 28840|
12|2016-06-22| 32836|
13|2016-06-23| 44268|
Output:
match_no|match_date|audience|
--------|----------|--------|
6|2016-06-16| 63670|
7|2016-06-17| 73648|
8|2016-06-18| 52409|
9|2016-06-19| 67291|
21. From the following table write a SQL query to know the availability of the doctor for
consecutive 2 or more days. Return visiting days.
Input:
Table: dr_clinic
visiting_date|availability|
-------------|------------|
2016-06-11| 1|
2016-06-12| 1|
2016-06-13| 0|
2016-06-14| 1|
2016-06-15| 0|
2016-06-16| 0|
2016-06-17| 1|
2016-06-18| 1|
2016-06-19| 1|
2016-06-20| 1|
2016-06-21| 1|
Output:
visiting_date|
-------------|
2016-06-11|
2016-06-12|
2016-06-17|
2016-06-18|
2016-06-19|
2016-06-20|
2016-06-21|
22. From the following tables find those customers who did not make any order to the
supplier 'DCX LTD'. Return customers name.
Input:
Table: customers
customer_id|customer_name|customer_city|avg_profit|
-----------|-------------|-------------|----------|
101|Liam |New York | 25000|
102|Josh |Atlanta | 22000|
103|Sean |New York | 27000|
104|Evan |Toronto | 15000|
105|Toby |Dallas | 20000|
Table : supplier
supplier_id|supplier_name|supplier_city|
-----------|-------------|-------------|
501|ABC INC |Dallas |
502|DCX LTD |Atlanta |
503|PUC ENT |New York |
504|JCR INC |Toronto |
Table: orders
order_id|customer_id|supplier_id|order_date|order_amount|
--------|-----------|-----------|----------|------------|
401| 103| 501|2012-03-08| 4500|
402| 101| 503|2012-09-15| 3650|
403| 102| 503|2012-06-27| 4800|
404| 104| 502|2012-06-17| 5600|
405| 104| 504|2012-06-22| 6000|
406| 105| 502|2012-06-25| 5600|
Output:
customer_name|
-------------|
Liam |
Josh |
Sean |
----------------------

23. Table students contain marks of mathematics for several students in a class. It may same
marks for more than one student.
From the following table write a SQL table to find the highest unique marks a student
achieved. Return the marks.
Table: students
student_id|student_name|marks_achieved|
----------|------------|--------------|
1|Alex | 87|
2|Jhon | 92|
3|Pain | 83|
4|Danny | 87|
5|Paul | 92|
6|Rex | 89|
7|Philip | 87|
8|Josh | 83|
9|Evan | 92|
10|Larry | 87|
Output:
marks|
-----|
89|
24. In a hostel, each room contains two beds. After every 6 months a student have to change
their bed with his or her room-mate.
From the following tables write a SQL query to find the new beds of the students in the
hostel. Return original_bed_id, student_name, bed_id and student_new.
Table : bed_info
bed_id|student_name|
------|------------|
101|Alex |
102|Jhon |
103|Pain |
104|Danny |
105|Paul |
106|Rex |
107|Philip |
108|Josh |
109|Evan |
110|Green |
Output:
original_bed_id|student_name|bed_id|student_new|
---------------|------------|------|-----------|
102|Jhon | 101|Jhon |
101|Alex | 102|Alex |
104|Danny | 103|Danny |
103|Pain | 104|Pain |
106|Rex | 105|Rex |
105|Paul | 106|Paul |
108|Josh | 107|Josh |
107|Philip | 108|Philip |
110|Green | 109|Green |
109|Evan | 110|Evan |
25. From the following table, write a SQL query to find the first login date for each customer.
Return customer id, login date.
Input:
Table: bank_trans
trans_id|customer_id|login_date|
--------|-----------|----------|
101| 3002|2019-09-01|
101| 3002|2019-08-01|
102| 3003|2018-09-13|
102| 3002|2018-07-24|
103| 3001|2019-09-25|
102| 3004|2017-09-05|
Output:
customer_id|first_login|
-----------|-----------|
3001| 2019-09-25|
3002| 2018-07-24|
3003| 2018-09-13|
3004| 2017-09-05|
26. From the following table, write a SQL query to find those salespersons whose
commission is less than ten thousand. Return salesperson name, commission.
Input:
Table: salemast
salesman_id|salesman_name|yearly_sale|
-----------|-------------|-----------|
101|Adam | 250000|
103|Mark | 100000|
104|Liam | 200000|
102|Evan | 150000|
105|Blake | 275000|
106|Noah | 50000|
Table : commision
salesman_id|commision_amt|
-----------|-------------|
101| 10000|
103| 4000|
104| 8000|
102| 6000|
105| 11000|
Output:
salesman_name|commision_amt|
-------------|-------------|
Mark | 4000|
Liam | 8000|
Evan | 6000|
27. From the following table write a SQL query to find those distributors who purchased all
types of item from the company. Return distributors ids.
Input:
Table: items
item_code|item_name|
---------|---------|
10091|juice |
10092|chocolate|
10093|cookies |
10094|cake |
Table : orders
order_id|distributor_id|item_ordered|item_quantity|
--------|--------------|------------|-------------|
1| 501| 10091| 250|
2| 502| 10093| 100|
3| 503| 10091| 200|
4| 502| 10091| 150|
5| 502| 10092| 300|
6| 504| 10094| 200|
7| 503| 10093| 250|
8| 503| 10092| 250|
9| 501| 10094| 180|
10| 503| 10094| 350|
Output:
distributor_id|
--------------|
503|
28. From the following tables write a SQL query to find those directors and actors who
worked together at least three or more movies. Return the director and actor name.
Input:
Table: actor_test
act_id|act_name |
------|-----------------|
101|James Stewart |
102|Deborah Kerr |
103|Peter OToole |
104|Robert De Niro |
105|F. Murray Abraham|
106|Harrison Ford |
107|Bill Paxton |
108|Stephen Baldwin |
109|Jack Nicholson |
110|Mark Wahlberg |
Table : director_test
dir_id|dir_name |
------|-----------------|
201|Alfred Hitchcock |
202|Jack Clayton |
203|James Cameron |
204|Michael Cimino |
205|Milos Forman |
206|Ridley Scott |
207|Stanley Kubrick |
208|Bryan Singer |
209|Roman Polanski |
Table: movie_test
mov_id|movie_name |
------|-------------------|
901|Vertigo |
902|Aliens |
903|Lawrence of Arabia |
904|The Deer Hunter |
905|True Lies |
906|Blade Runner |
907|Eyes Wide Shut |
908|Titanic |
909|Chinatown |
910|Ghosts of the Abyss|
Table : mov_direction_test
dir_id|mov_id|act_id|
------|------|------|
201| 901| 101|
203| 902| 107|
204| 904| 104|
203| 905| 107|
206| 906| 106|
203| 908| 107|
209| 909| 109|
203| 910| 107|
Output:
dir_name |act_name |
-------------|-----------|
James Cameron|Bill Paxton|
29. From the following tables write a SQL query to find those students who achieved 100
percent in various subjects in every year. Return examination ID, subject name, examination
year, number of students.
Input:
Table: exam_test
exam_id|subject_id|exam_year|no_of_student|
-------|----------|---------|-------------|
71| 201| 2017| 5146|
71| 201| 2018| 3545|
71| 202| 2018| 5945|
71| 202| 2019| 2500|
71| 203| 2017| 2500|
72| 201| 2018| 3500|
72| 202| 2017| 3651|
73| 201| 2018| 2647|
73| 201| 2019| 2647|
73| 202| 2018| 4501|
Table : subject_test
subject_id|subject_name|
----------|------------|
201|Mathematics |
202|Physics |
203|Chemistry |
Output:
exam_id|subject_name|exam_year|no_of_student|
-------|------------|---------|-------------|
71|Chemistry | 2017| 2500|
71|Mathematics | 2017| 5146|
71|Mathematics | 2018| 3545|
71|Physics | 2018| 5945|
71|Physics | 2019| 2500|
72|Mathematics | 2018| 3500|
72|Physics | 2017| 3651|
73|Mathematics | 2018| 2647|
73|Mathematics | 2019| 2647|
73|Physics | 2018| 4501|
30. From the following tables write a SQL query to find those students who achieved 100
percent marks in every subject for all the year. Return subject ID, subject name, students for
all year.
Input:
Table: exam_test
exam_id|subject_id|exam_year|no_of_student|
-------|----------|---------|-------------|
71| 201| 2017| 5146|
71| 201| 2018| 3545|
71| 202| 2018| 5945|
71| 202| 2019| 2500|
71| 203| 2017| 2500|
72| 201| 2018| 3500|
72| 202| 2017| 3651|
73| 201| 2018| 2647|
73| 201| 2019| 2647|
73| 202| 2018| 4501|
Table : subject_test
subject_id|subject_name|
----------|------------|
201|Mathematics |
202|Physics |
203|Chemistry |
Output:
subject_id|subject_name|Students for all year|
----------|------------|---------------------|
201|Mathematics | 17485|
202|Physics | 16597|
203|Chemistry | 2500|
31. From the following tables write a SQL query that will generate a report which shows the
total number of students achieved 100 percent for the first year of each examination of every
subject.
Input:
Table: exam_test
exam_id|subject_id|exam_year|no_of_student|
-------|----------|---------|-------------|
71| 201| 2017| 5146|
71| 201| 2018| 3545|
71| 202| 2017| 2701|
71| 202| 2018| 5945|
71| 202| 2019| 2500|
71| 203| 2017| 2500|
72| 201| 2018| 3500|
72| 202| 2017| 3651|
73| 201| 2017| 1000|
73| 201| 2018| 2647|
73| 201| 2019| 2647|
73| 202| 2018| 4501|
Table : subject_test
subject_id|subject_name|
----------|------------|
201|Mathematics |
202|Physics |
203|Chemistry |
Output:
exam_id|subject_name|first_year|no_of_student|
-------|------------|----------|-------------|
71|Mathematics | 2017| 5146|
71|Physics | 2017| 2701|
71|Chemistry | 2017| 2500|
72|Physics | 2017| 3651|
73|Mathematics | 2017| 1000|
32. From the following tables write a SQL query to display those managers who have average
experience for each scheme.
Input:
Table: managing_body
manager_id|manager_name|running_years|
----------|------------|-------------|
51|James | 5|
52|Cork | 3|
53|Paul | 4|
54|Adam | 3|
55|Hense | 4|
56|Peter | 2|
Table : scheme
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1001| 53|
1001| 54|
1001| 56|
1002| 51|
1002| 55|
1003| 51|
1004| 52|
Output:
scheme_code|Average year of experience|
-----------|--------------------------|
1001| 3.50|
1002| 4.50|
1003| 5.00|
1004| 3.00|
33. From the following tables write a SQL query to find those schemes which executed by
minimum number of employees. Return scheme code.
Input:
Table: managing_body
manager_id|manager_name|running_years|
----------|------------|-------------|
51|James | 5|
52|Cork | 3|
53|Paul | 4|
54|Adam | 3|
55|Hense | 4|
56|Peter | 2|
Table : scheme
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1001| 53|
1001| 54|
1001| 56|
1002| 51|
1002| 55|
1003| 51|
1004| 52|
Output:
scheme_code|
-----------|
1003|
1004|
34. From the following tables write a SQL query to find those experienced manager who
execute the schemes. Return scheme code and scheme manager ID.
Input:
Table: managing_body
manager_id|manager_name|running_years|
----------|------------|-------------|
51|James | 5|
52|Cork | 3|
53|Paul | 4|
54|Adam | 3|
55|Hense | 4|
56|Peter | 2|
Table : scheme
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1001| 53|
1001| 54|
1001| 56|
1002| 51|
1002| 55|
1003| 51|
1004| 52|
Output:
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1002| 51|
1003| 51|
1004| 52|
35. From the following tables write an SQL query to find the best seller by total sales price.
Return distributor ID , If there is a tie, report them all.
Input:
Table: item
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table : sales_info
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-02-12| 3| 8100|
5001| 103| 1002| 2020-03-15| 15| 4500|
5002| 101| 1001| 2019-06-24| 2| 5400|
5001| 104| 1003| 2019-09-11| 8| 2400|
5003| 101| 1003| 2020-10-21| 5| 13500|
5003| 104| 1002| 2020-12-27| 10| 3000|
5002| 102| 1001| 2019-05-18| 12| 9600|
5002| 103| 1004| 2020-06-17| 8| 2400|
5003| 103| 1001| 2020-04-12| 3| 900|
Output:
distributor_id|
--------------|
5002|
5003|
36. From the following table write a SQL query to find those retailers who have bought 'key
board' but not 'mouse'. Return retailer ID.
Input:
Table: item
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table : sales_info
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-02-12| 3| 8100|
5001| 103| 1002| 2020-03-15| 15| 4500|
5002| 101| 1001| 2019-06-24| 2| 5400|
5001| 104| 1003| 2019-09-11| 8| 2400|
5003| 101| 1003| 2020-10-21| 5| 13500|
5003| 104| 1002| 2020-12-27| 10| 3000|
5002| 102| 1001| 2019-05-18| 12| 9600|
5002| 103| 1004| 2020-06-17| 8| 2400|
5003| 103| 1001| 2020-04-12| 3| 900|
Output:
retailer_id|
-----------|
1001|
1004|
37. From the following table write a SQL query to display those items that were only sold in
the 2nd quarter of a year, i.e. April 1st to June end for the year 2020. Return item code and
item description.
Input:
Table: item
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table : sales_info
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-02-12| 3| 8100|
5001| 103| 1002| 2020-03-15| 15| 4500|
5002| 101| 1001| 2019-06-24| 2| 5400|
5001| 104| 1003| 2019-09-11| 8| 2400|
5003| 101| 1003| 2020-10-21| 5| 13500|
5003| 104| 1002| 2020-12-27| 10| 3000|
5002| 102| 1001| 2019-05-18| 12| 9600|
5002| 103| 1004| 2020-06-17| 8| 2400|
5003| 103| 1001| 2020-04-12| 3| 900|
Output:
item_code|item_desc |
---------|------------|
101|mother board|
102|RAM |
103|key board |
38. From the following table write a SQL query to find the highest purchase with its
corresponding item for each customer. In case of a same quantity purchase find the item code
which is smallest.
The output must be sorted by increasing of customer_id. Return customer ID,lowest item
code and purchase quantity.
Input:
Table: purchase
Field |Type |Null|Key|Default|Extra|
-----------|-------|----|---|-------|-----|
customer_id|int(11)|NO | | | |
item_code |int(11)|NO | | | |
purch_qty |int(11)|NO | | | |
Data:
customer_id|item_code|purch_qty|
-----------|---------|---------|
101| 504| 25|
101| 503| 50|
102| 502| 40|
102| 503| 25|
102| 501| 45|
103| 505| 30|
103| 503| 25|
104| 505| 40|
101| 502| 25|
102| 504| 40|
102| 505| 50|
103| 502| 25|
104| 504| 40|
103| 501| 35|
Output:
customer_id|lowest item code|purch_qty|
-----------|----------------|---------|
101| 503| 50|
102| 505| 50|
103| 501| 35|
104| 504| 40|
39. From the following table write a SQL query to find all the writers who rated at least one
of their own topic. Sorted the result in ascending order by writer id. Return writer ID.
Input:
Table: topics
Field |Type |Null|Key|Default|Extra|
--------------|-------|----|---|-------|-----|
topic_id |int(11)|YES | | | |
writer_id |int(11)|YES | | | |
rated_by |int(11)|YES | | | |
date_of_rating|date |YES | | | |
Data:
topic_id|writer_id|rated_by|date_of_rating|
-------|---------|--------|--------------|
10001| 504| 507| 2020-07-17|
10003| 502| 503| 2020-09-22|
10001| 503| 507| 2020-02-07|
10002| 501| 507| 2020-05-13|
10002| 502| 502| 2020-04-10|
10002| 504| 502| 2020-11-16|
10003| 501| 502| 2020-10-05|
10001| 507| 507| 2020-12-23|
10004| 503| 501| 2020-08-28|
10003| 505| 504| 2020-12-21|
Output:
Author rated on own topic|
-------------------------|
502|
507|
40. From the following table write a SQL query to find all the writers who rated more than
one topics on the same date, sorted in ascending order by their id. Return writr ID.
Input:
Table: topics
Field |Type |Null|Key|Default|Extra|
--------------|-------|----|---|-------|-----|
topic_id |int(11)|YES | | | |
writer_id |int(11)|YES | | | |
rated_by |int(11)|YES | | | |
date_of_rating|date |YES | | | |
Data:
topic_id|writer_id|rated_by|date_of_rating|
-------|---------|--------|--------------|
10001| 504| 507| 2020-07-17|
10003| 502| 503| 2020-09-22|
10001| 503| 507| 2020-02-07|
10002| 501| 507| 2020-05-13|
10002| 502| 502| 2020-04-10|
10002| 504| 502| 2020-11-16|
10003| 501| 502| 2020-10-05|
10001| 507| 507| 2020-12-23|
10004| 503| 501| 2020-08-28|
10003| 505| 504| 2020-12-21|
Output:
Topic rated by the writer|
-------------------------|
502|
507|
41. From the following table write a SQL query to make a report such that there is a product
id column and a sale quantity column for each quarter. Return product ID and sale quantity of
each quarter.
Input:
Table: sale
Field |Type |Null|Key|Default|Extra|
----------|-----------|----|---|-------|-----|
product_id|int(11) |NO |PRI| | |
sale_qty |int(11) |YES | | | |
qtr_no |varchar(25)|NO |PRI| | |
Data:
product_id|sale_qty|qtr_no|
----------|--------|------|
1| 15000|qtr1 |
1| 10000|qtr2 |
2| 20000|qtr1 |
2| 12000|qtr2 |
3| 20000|qtr1 |
3| 15000|qtr2 |
3| 23000|qtr3 |
3| 22000|qtr4 |
4| 25000|qtr2 |
4| 18000|qtr4 |
Output:
product_id qtr1_sale qtr2_sale qtr3_sale qtr4_sale
1 15000 10000 NULL NULL
2 20000 12000 NULL NULL
3 20000 15000 23000 22000
4 NULL 25000 NULL 18000
42. From the following table write a SQL query to find for each month and company, the
number of orders issued and their total quantity, the number of orders booked and their total
order quantity. Return month, name of the company, number of orders issued, number of
booked orders, total order quantity and total booked orders quantity.
Input:
Table: order_stat
Field |Type |Null|Key|Default|Extra|
---------|-----------|----|---|-------|-----|
order_id |int(11) |NO |PRI| | |
com_name |varchar(25)|YES | | | |
ord_qty |int(11) |YES | | | |
ord_stat |varchar(25)|YES | | | |
stat_date|date |YES | | | |
Data:
order_id|com_name |ord_qty|ord_stat |stat_date |
--------|-----------|-------|---------|----------|
151|MMS INC | 500|Booked |2020-08-15|
152|BCT LTD | 300|Cancelled|2020-08-15|
153|MMS INC | 400|Cancelled|2020-08-26|
154|XYZ COR | 500|Booked |2020-08-15|
155|MMS INC | 500|Cancelled|2020-10-11|
156|BWD PRO LTD| 250|Cancelled|2020-11-15|
157|BCT LTD | 600|Booked |2020-10-07|
158|MMS INC | 300|Booked |2020-12-11|
159|XYZ COR | 300|Booked |2020-08-26|
160|BCT LTD | 400|Booked |2020-11-15|
Output:
month year com_name no_of_orders booked_orders total_order_qty
no_of_booked_qty
2020-08 MMS INC 2 1 900
500
2020-08 BCT LTD 1 0 300
0
2020-08 XYZ COR 2 2 800
800
2020-10 MMS INC 1 0 500
0
2020-11 BWD PRO LTD 1 0 250
0
2020-10 BCT LTD 1 1 600
600
2020-12 MMS INC 1 1 300
300
2020-11 BCT LTD 1 1 400
400
43. From the following table write a SQL query to find for each month and company, the
number of orders issued and their total quantity, the number of orders cancelled and their
total quantity. Return month, name of the company, number of orders booked, number of
booked quantity, number of cancelled order, and number of cancelled quantity.
Input:
Table: order_stat
Field |Type |Null|Key|Default|Extra|
---------|-----------|----|---|-------|-----|
order_id |int(11) |NO |PRI| | |
com_name |varchar(25)|YES | | | |
ord_qty |int(11) |YES | | | |
ord_stat |varchar(25)|YES | | | |
stat_date|date |YES | | | |
Data:
order_id|com_name |ord_qty|ord_stat |stat_date |
--------|-----------|-------|---------|----------|
151|MMS INC | 500|Booked |2020-08-15|
152|BCT LTD | 300|Cancelled|2020-08-15|
153|MMS INC | 400|Cancelled|2020-08-26|
154|XYZ COR | 500|Booked |2020-08-15|
155|MMS INC | 500|Cancelled|2020-10-11|
156|BWD PRO LTD| 250|Cancelled|2020-11-15|
157|BCT LTD | 600|Booked |2020-10-07|
158|MMS INC | 300|Booked |2020-12-11|
159|XYZ COR | 300|Booked |2020-08-26|
160|BCT LTD | 400|Booked |2020-11-15|
Table: order_return
Structure:
Field Type Null Key Default Extra
order_id int(11) NO MUL
return_date date YES
Data:
order_id return_date
153 2020-10-12
154 2020-11-07
156 2020-12-05
159 2020-09-17
Output:
month |com_name |booked_count|booked_qty|cancelled_count|cancelled_qty|
-------|-----------|------------|----------|---------------|-------------|
2020-08|BCT LTD | 0| 0.0| 1| 300.0|
2020-08|MMS INC | 1| 500.0| 1| 400.0|
2020-08|XYZ COR | 2| 800.0| 0| 0.0|
2020-10|BCT LTD | 1| 600.0| 0| 0.0|
2020-10|MMS INC | 0| 0.0| 1| 500.0|
2020-11|BCT LTD | 1| 400.0| 0| 0.0|
2020-11|BWD PRO LTD| 0| 0.0| 1| 250.0|
2020-12|MMS INC | 1| 300.0| 0| 0.0|
44. From the following tables write a SQL query to find the average selling price for each
item. Return item code and average_selling_price. average_selling_price should be rounded
to 2 decimal places.
Input:
Table: item_price
Field |Type |Null|Key|Default|Extra|
---------|-------|----|---|-------|-----|
item_code|int(11)|YES | | | |
date_from|date |YES | | | |
date_to |date |YES | | | |
item_cost|int(11)|YES | | | |
Data:
item_code|date_from |date_to |item_cost|
---------|----------|----------|---------|
101|2018-04-07|2018-06-28| 8|
102|2018-02-15|2018-04-17| 13|
103|2018-03-12|2018-04-30| 10|
101|2018-06-29|2018-10-31| 15|
103|2018-05-01|2019-08-24| 14|
102|2018-04-18|2018-07-10| 25|
104|2018-06-11|2018-10-10| 25|
101|2018-11-01|2019-01-15| 20|
Table: sale
Structure:
Field Type Null Key Default Extra
sale_date date YES
item_code int(11) YES
sale_qty int(11) YES
Data:
sale_date item_code sale_qty
2018-05-15 101 120
2018-04-27 103 80
2018-04-10 102 200
2018-07-12 101 100
2018-07-07 103 50
2018-09-17 104 100
2018-06-25 102 100
Output:
item_code|average_selling_price|
---------|---------------------|
101| 11.18|
102| 17.00|
103| 11.54|
104| 25.00|
45. From the following table write a SQL query to find all employees that directly or
indirectly report to the head of the company. Return employee_id, name, and manager_id.
Input:
Table: emp_test_table
Field |Type |Null|Key|Default|Extra|
-----------|-----------|----|---|-------|-----|
employee_id|int(11) |NO |PRI| | |
first_name |varchar(25)|YES | | | |
manager_id |int(11) |YES | | | |
Data:
employee_id|first_name |manager_id|
-----------|-----------|----------|
100|Steven | 100|
101|Neena | 100|
102|Lex | 100|
103|Alexander | 102|
104|Bruce | 103|
105|David | 103|
106|Valli | 103|
107|Diana | 103|
108|Nancy | 101|
109|Daniel | 108|
110|John | 108|
Output:
employee_id|Name |manager_id|
-----------|-----------|----------|
101|Neena | 100|
102|Lex | 100|
103|Alexander | 102|
104|Bruce | 103|
105|David | 103|
106|Valli | 103|
107|Diana | 103|
108|Nancy | 101|
109|Daniel | 108|
110|John | 108|
46. From the following tables write a SQL query to find the number of times each patient call
the specialist doctor since their treating period. Order the result table by patient_id and
specialist_call.
Input:
Table: patient
Field |Type |Null|Key|Default|Extra|
------------|-----------|----|---|-------|-----|
patient_id |int(11) |NO |PRI| | |
patient_name|varchar(25)|YES | | | |
Data:
patient_id|patient_name |
----------|---------------|
1001|Gilbart Kane |
1002|Thomas Richi |
1003|Ricardo Grance |
1004|Vanio Tishuma |
1005|Charls Brown |
Table: speciality
Field |Type |Null|Key|Default|Extra|
----------|-----------|----|---|-------|-----|
specialist|varchar(25)|YES | | | |
Data:
specialist |
-----------|
medicine |
cardiology |
neurology |
hematology |
Table: treatment
Field |Type |Null|Key|Default|Extra|
---------------|-----------|----|---|-------|-----|
patient_id |int(11) |YES |MUL| | |
specialist_call|varchar(25)|YES | | | |
Data:
patient_id|specialist_call|
----------|---------------|
1001|medicine |
1003|medicine |
1002|cardiology |
1001|hematology |
1004|medicine |
1003|cardiology |
1005|neurology |
1002|neurology |
1001|cardiology |
1005|cardiology |
1003|cardiology |
1005|hematology |
1004|hematology |
1005|neurology |
1002|neurology |
1001|hematology |
Output:
patient_id|patient_name |specialist |Specialist Attended|
----------|---------------|-----------|-------------------|
1001|Gilbart Kane |cardiology | 1|
1001|Gilbart Kane |hematology | 2|
1001|Gilbart Kane |medicine | 1|
1001|Gilbart Kane |neurology | 0|
1002|Thomas Richi |cardiology | 1|
1002|Thomas Richi |hematology | 0|
1002|Thomas Richi |medicine | 0|
1002|Thomas Richi |neurology | 2|
1003|Ricardo Grance |cardiology | 2|
1003|Ricardo Grance |hematology | 0|
1003|Ricardo Grance |medicine | 1|
1003|Ricardo Grance |neurology | 0|
1004|Vanio Tishuma |cardiology | 0|
1004|Vanio Tishuma |hematology | 1|
1004|Vanio Tishuma |medicine | 1|
1004|Vanio Tishuma |neurology | 0|
1005|Charls Brown |cardiology | 1|
1005|Charls Brown |hematology | 1|
1005|Charls Brown |medicine | 0|
1005|Charls Brown |neurology | 2|
47. From the following table write a SQL query to find the number of employees are working
in the department of each employees. Return employee Id and number of employees are
working in their department.
Input:
Table: emp_test_table
Field |Type |Null|Key|Default|Extra|
-----------|-----------|----|---|-------|-----|
employee_id|int(11) |NO |PRI| | |
first_name |varchar(25)|YES | | | |
manager_id |int(11) |YES | | | |
Data:
employee_id|first_name |department_id|
-----------|-----------|-------------|
100|Steven | 90|
101|Neena | 90|
102|Lex | 90|
103|Alexander | 60|
104|Bruce | 60|
105|David | 60|
106|Valli | 60|
107|Diana | 60|
108|Nancy | 100|
109|Daniel | 100|
110|John | 100|
Output:
employee_id|employees_in_department|
-----------|-----------------------|
100| 3|
101| 3|
102| 3|
103| 5|
104| 5|
105| 5|
106| 5|
107| 5|
108| 3|
109| 3|
110| 3|
48. From the following table write a SQL query to find the total sale quantity of items of each
unit type at each day. Return unit type, date and total sale quantity at each day. Order the
result table by gender and day.
Input:
Table: sale
Field |Type |Null|Key|Default|Extra|
------------|-----------|----|---|-------|-----|
product_name|varchar(25)|YES | | | |
unit_type |varchar(5) |YES | | | |
sale_date |date |YES | | | |
sale_qty |int(11) |YES | | | |
Data:
product_name |unit_type|sale_date |sale_qty|
---------------|---------|----------|--------|
Munchos |P |2018-05-15| 20|
Boyer Chocolate|P |2018-04-27| 30|
CocaCola |L |2018-04-10| 25|
Fruit Cakes |P |2018-07-12| 30|
CocaCola |L |2018-07-07| 50|
Fanta |L |2018-01-27| 70|
Chex Mix |P |2018-09-17| 40|
Jaffa Cakes |P |2018-06-25| 40|
Pom-Bear |P |2018-02-11| 30|
Twix Chocolate |P |2018-12-24| 50|
Limca |L |2018-03-15| 50|
Mirinda |L |2018-02-05| 40|
Output:
unit_type|sale_date |running unit|
---------|----------|------------|
L |2018-01-27| 70|
L |2018-02-05| 110|
L |2018-03-15| 160|
L |2018-04-10| 185|
L |2018-07-07| 235|
P |2018-02-11| 30|
P |2018-04-27| 60|
P |2018-05-15| 80|
P |2018-06-25| 120|
P |2018-07-12| 150|
P |2018-09-17| 190|
P |2018-12-24| 240|
49. From the following tables write a SQL query to get the description of items with 50 or
more quantities sold out within January and February of 2020. Return item description and
sale quantity.
Input:
Table: item
Field |Type |Null|Key|Default|Extra|
---------|------------|----|---|-------|-----|
item_code|int(11) |NO |PRI| | |
item_desc|varchar(255)|YES | | | |
cost |int(11) |YES | | | |
Data:
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table: sales_info
Field |Type |Null|Key|Default|Extra|
--------------|-------|----|---|-------|-----|
distributor_id|int(11)|YES | | | |
item_code |int(11)|YES | | | |
retailer_id |int(11)|YES | | | |
date_of_sell |date |YES | | | |
quantity |int(11)|YES | | | |
total_cost |int(11)|YES | | | |
Data:
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-01-12| 30| 8100|
5001| 103| 1002| 2020-01-15| 25| 4500|
5002| 101| 1001| 2019-01-30| 25| 5400|
5001| 104| 1003| 2019-02-17| 75| 2400|
5003| 101| 1003| 2020-03-07| 55| 13500|
5003| 104| 1002| 2020-05-27| 100| 3000|
5002| 102| 1001| 2020-05-18| 65| 9600|
5002| 103| 1004| 2020-01-30| 45| 2400|
5003| 103| 1001| 2020-03-12| 30| 900|
Output:
item_desc |sale_quantity|
------------|-------------|
key board | 70|
mother board| 55|
mouse | 75|
50. From the following table write a SQL query to find the order id and the item name for all
companies who are not registered with the distributor. Return the result table in any order.
Input:
Table: company_info
Field |Type |Null|Key|Default|Extra|
------------|-----------|----|---|-------|-----|
company_id |int(11) |NO |PRI| | |
company_name|varchar(25)|YES | | | |
Data:
company_id|company_name|
----------|------------|
5001|Intel |
5002|Kingston |
5003|Dell |
5004|Sony |
5005|Iball |
5006|Canon |
Table: orders
Field |Type |Null|Key|Default|Extra|
----------|-----------|----|---|-------|-----|
order_id |int(11) |YES | | | |
item_name |varchar(25)|YES | | | |
company_id|int(11) |YES | | | |
Data:
order_id|item_name |company_id|
--------|-------------|----------|
101|mother board | 5001|
102|RAM | 5002|
103|printer | 5006|
104|keyboard | 5005|
105|mouse | 6051|
106|speaker | 6009|
107|web cam | 5005|
108|hard disk | 5002|
109|monitor | 5003|
110|scanner | 7023|
Output:
order_id|item_name|
--------|---------|
105|mouse |
106|speaker |
110|scanner |

You might also like