0% found this document useful (0 votes)
54 views93 pages

Interview PDF CM

The document contains a comprehensive list of interview questions and sample answers across various categories including HR questions, project-based questions, internship-related inquiries, and data structure concepts. It provides insights into how candidates can effectively respond to common interview scenarios and articulate their experiences, strengths, and aspirations. Additionally, it includes suggested final year projects and explanations of data structures, emphasizing their importance in programming.

Uploaded by

Sayantan Laha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views93 pages

Interview PDF CM

The document contains a comprehensive list of interview questions and sample answers across various categories including HR questions, project-based questions, internship-related inquiries, and data structure concepts. It provides insights into how candidates can effectively respond to common interview scenarios and articulate their experiences, strengths, and aspirations. Additionally, it includes suggested final year projects and explanations of data structures, emphasizing their importance in programming.

Uploaded by

Sayantan Laha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 93

Interview Pdf 1 - HR QUESTIONS

Q1. Tell me about yourself.


Sample Answer:
Thank you, Sir/Ma’am for this opportunity. I perceive myself as a confident, conscientious and
hardworking individual. I have done ABC project with XYZ programming language. I have
completed
my internship from QRS Company on the topic UVW. I love to listen music in my free time,
aright
Singh being my favourite singer. I carry out any task assigned to me without hesitation, In the
case of
doubts; I never hesitate to put forth my questions. I have always been a fast learner, and I love
to
keep up my process of learning to figure out better ways of solving problems.
Q2. Why do you want to work for our company?
Sample Answer:
I feel that with my current skill sets and my experience in the XYZ domain, the job requirements
this
role presented are a perfect match for me. I could visualize myself in that role as it aligned with
my
career aspirations, skills, and expertise. Besides, I have researched your company and found
that it
has impressive and promising projections which made me excited to be a part of the amazing
future.
I would take pride in working under the great leadership of this company and I found this place
to be
a perfect fit for utilizing my expertise along with the promising aspect of personal growth.
Q3. What are your greatest strengths and weaknesses?
Sample Answer:
I think one of my greatest strengths is that I am a great team player. I am also a self-motivated
and
quick learning individual. Whatever task that I set to do, I always give my best and complete it
diligently well in advance. My weakness would be that I am learning to master people skills
while
meeting new individuals. I get nervous while talking to new people. I have been working on this
for
quite a long time and I can say with utmost confidence that I have come a long way.
Q4. How would you rate yourself on a scale of 1 to 10?
Sample Answer:
- HR Questions

I would like to rate myself an 8. Because I know that I am not perfect and there is always a
scope for
learning and improvement. Continuous learning is the most fundamental part of personal and
professional growth.
Q5. Where do you see yourself in the next 5 years?
Sample Answer:
Over five years, I'd love to take advantage of every opportunity the company will give me to gain
knowledge through the external and internal training programs. My dream career objective is to
be
a developer. Hence, I am looking forward to creating different products that embody the mission
of
this company and contribute to making a positive impact while speeding up my path to
becoming a
software developer.
Q6. Would you like to work overtime or odd hours?
Sample Answer:
I understand that putting extra effort impacts the company's development, so I'm happy. If it
means
I'm contributing to the company, I'll be glad to contribute.
Q7. Why should we hire you?
Sample Answer:
I am a self-motivated and very open-minded person who can learn very fast. Looking at the job
description, I am confident that I am very much suitable for this role. I enjoy solving problems
and I
am a great team player. I also believe that my values are aligned with this company’s values. I
think
this position will support my interest and also give me interesting and exciting opportunities to
contribute to the growth of this organization. I am very much excited about this opportunity.
Q8. How do you deal with criticism?

Sample Answer:
I am always enthusiastic about learning new things and during the process, I might tend to
make
mistakes. If someone provides me with constructive criticism, I am always open to it and I will
work
on correcting myself and learn from my mistakes. This would help me grow and move forward. If
the
feedback is negative, then I am mature enough to ignore the feedback and continue working on
doing my job to the best of my capabilities without dampening my spirit.
Q9. Do you lie?
Sample Answer:
It totally depends on the situation but more preferably I will find out the other solution to the
problem which is beneficial for me and my company as well; instead of speaking lie. Because
every
problem has a solution. Assume that, if I will lie for the company but sooner or later one-day
truth
will reveal then the reputation of my company will be disputed.
Note: If you say you don’t lie, then that will be the biggest lie and make you come across as
someone
who cannot be entirely trusted. Talk about an instance when you lied and make sure it is not
about a
major lie but an innocent, white lie.
Q10. How much salary are you expecting?
Sample Answer:
I know I am just starting off my professional career, however, my personal salary expectation is
around 25-30K in-hand. Salary is important. However, at my stage, I am more interested in
finding
the right position and work than the salary. And it would be helpful if you could share your
estimate
for this role.
Q11. Do you have any questions for me?
Sample Answer:
Yes, First of all, thank you for giving me this opportunity. I would like to know which areas I need
to
improve myself. Can you share more about day to day responsibilities of this role? What are the
extra skills and knowledge required for this job role?
Q12. What are your goals and aspirations in life?
Sample Answer:
Currently, my short-term goal is to nail this interview and get placed in a reputed company like
yours, and my long-term goals are to climb up the ladder and see myself as a software
developer
within the company, who has nourished the edge technology and skills.
Q13. What motivated you to do your job well?
Sample Answer:
I am always motivated to do a task to the best abilities. My father had told me at a young age
that
whenever you do a task with your name attached to it, you must do it with 200% of your
dedication
because it might continue to live longer than you. You must do it to your best abilities for it to be
memorable.
Q14. Who is your inspiration?
Sample Answer:
While there are countless individuals that I have met in my life who can be a source of
inspiration for
me- from my teachers to my parents however the biggest inspiration I get is from myself. You
see, I
try to picture myself in 10 years and create an image of my life there and work tirelessly to reach
that image. However, I have already constructed another image for myself as I reach that
image,
which is ten years away. So, I always try to achieve higher than what I have made for myself
and that
picture of me in 10 years keeps me motivated.
Q15. Define success

Sample Answer:
Success for me is a journey that is full of obstacles. These obstacles come in the form of
learnings
which I turn into springboards during my run to the finish line. But I believe that if today is better
than yesterday, I have succeeded in my work and life.
Q16. What was the toughest decision you’ve had to make?
Sample Answer:
I always calculate my decisions by making a cost-benefit analysis of the available options.
Putting the
benefit to the cost of the decision helps me greatly in breaking down the toughness of the
decision
and allows me to weigh the pros and cons easily. But despite that I had had the toughest
decision
made when I was willing to get into a good university but due to bad financial condition I had to
end
up in ABC College. Howsoever, I have tried to utilize that opportunity as well.
Q17. Did you ever think of starting your own business?
Sample Answer:
I have always wanted to start a company of my own. But currently, I am a fresher and intend to
gain
some valuable skills for my overall development. Thus, I think I am not entirely ready to begin a
company of my own. However, the dream is still alive.
Q18. What do you expect from our company?
Sample Answer:
My primary aim is to learn from the company. So, I expect a lot of feedback on my work. As I
had
explained, I thrive on feedback as I understand the things I am doing wrong and, therefore, can
put
my mind to making them right.
Q19. Tell us about your hobbies and interests outside of work.
Sample Answer:

I am an avid reader and love reading ___ (author). I am also a big movie buff and try to catch
the
latest film in the theatre’s every Sunday with my friends and family. I am also a swimmer and
love to
relax by the pool on a sunny day.
Q20. What do you think is creativity?
Sample Answer:
Creativity, I believe, is in each one of us, from the drawing of a car by a 3-year-old to the great
Albert
Einstein. Creativity comes to us the minute we open our eyes and see the world as we only
fixate on
what attracts our attention.
Q21. Do you have a problem if we relocate you?
Sample Answer:
I’ve always had an urge to travel the world since my childhood. So, I don’t think relocation will
be a
major problem. It will be an adventure that I will look forward to. Though I will miss my family
and
friends back in my hometown, the internet world has made it easy to stay connected from any
part
of the country.
Q22. Can you handle work under pressure?
Sample Answer:
I have always loved playing the ____(instrument). I love it so much that I do not even panic or
come
under stress when playing to a large crowd. This is because I love playing the ____. Similarly, I
love
working in _____ (sales/marketing/etc), so I will never feel under pressure. If we love what we
do,
the pressure doesn’t affect us as it does to those who don’t love what they do.
Q23. How would you differentiate between confidence and overconfidence?

Sample Answer:
I believe confidence is the trust we have within ourselves and our ability to complete a task.
Overconfidence is the ego within us that surfaces when we think too highly of ourselves and
begin to
exaggerate our abilities.
Q24. Would you be willing to work overtime during nights and sometimes on weekends?
Sample Answer:
Like I have said, I always complete all the tasks assigned to me with due diligence. And if those
tasks
sometimes need me to come in on the weekend, I will not hesitate as my priority is always good
quality work.
Q25. Do you think you are overqualified for this position?
Sample Answer:
No, I don’t believe I am overqualified. As, I always think that there is always something to learn
everywhere. And I see a lot of exposure that I can gain for my development with your
organization.
So, I do not mind taking this job to learn more.

interview pdf 2 - Project Based Questions


Q1. Tell me what you learned from your project?
Q2. Why did you choose this project?
Q3. What were the objectives of the project?
Q4. What would happen if the client rejected your project proposal?
Q5. What are the limitations of your project?
Q6. If you were to start your project again, is there anything you would like to change?
Q7. What were the best features of your project?
Q8. Is there another possible explanation for the loopholes of your project?
Q9. What further research would you like to have conducted, and why?
Q10. How could it help people?

Q11. Can it be implemented in real-time?


Q12. Explain Working of all main logic of your code.
Q13. What is a project according to you?
Q14. Name five signs that indicate your project may fail.
Q15. Tell us about a project in which you participated and your role in that project.
Q16. Tell us about any creative idea or innovative solution you brought to a project.
Q17. What types of tools are involved in your project?
Q18. What is the team size of your project and how important was your role?
Q19. Explain your role in your team project.
Q20. What would you change in yourself when that comes to leading a team project?

Suggested Final Year Projects:


1. Gender and Age Detection System
2. ChatBot
3. Fraud Detection System
4. Movie Recommendations App
5. Online Library System
6. Web Development with Face Detection for security
7. Home Automation
8. Smart Parking
9. Truth and dare added alongside beer pong Game App
10. E-commerce website/App with AI enabled Bots for recommendation of goods as per
previous
search.
Interview Pdf 3 - internship/certification based question
Q1. Why have you applied for internship?
Q2. Why have you applied for an internship this company?
Q3. Why do you want to work in this industry?
Q4. Tell us about a time when you have successfully dealt with a difficult situation during your
internship.
Q5. What kept you interested in this internship?
Q6. What skills can you achieved from your internship?
Q7.Do you work better alone or with a team?
Q8. How would you describe your team at your internship work place?
Q9. What type of work environment do you prefer?
Q10. Rate yourself on basis of your performance and team work during the internship.

Q11. Tell me about a time when you worked with a difficult team member.
Q12. Tell me about a time when you successfully led a task assigned.
Q13. What Skills or Experiences Did you hope to Gain and could you achieve it?
Q14. Describe What’s Your Ideal Team?
Q15. Tell Us About a Situation Where You Took Initiative or Took on a Leadership Role during
internship.
Q16. Tell Us About an Assignment What Would You Have Done Differently?
Q17. Tell Us About a Time You Had to Learn Something Completely New.
Q18. Can You Tell Us About an Accomplishment You’re Proud of, and Why?
Q19. What can you bring to our company after this internship?
Q20. Tell me about a conflict that you’ve had witnessed at the internship and how would you
resolve
it.

Pdf 9 - Data Structure based Questions


Q1. What are Data Structures?
Answer:
A data structure is a mechanical or logical way that data is organized within a program.
The organization of data is what determines how a program performs. There are many
types of data structures, each with its own uses. When designing code, we need to pay
particular attention to the way data is structured. If data isn't stored efficiently or
correctly
structured, then the overall performance of the code will be reduced.
Q2. Why Create Data Structures?
Answer:
Data structures serve a number of important functions in a program. They ensure that
each line of code performs its function correctly and efficiently, they help the
programmer
identify and fix problems with his/her code, and they help to create a clear and
organized
code base.
Q3. What are some applications of Data structures?
Answer:
• Decision Making
• Genetics
• Image Processing
• Blockchain
• Numerical and Statistical Analysis
• Compiler Design
• Database Design and many more
Q4. Explain the process behind storing a variable in memory.
Answer:
• A variable is stored in memory based on the amount of memory that is needed.
Following are the steps followed to store a variable:
• The required amount of memory is assigned first.
• Then, it is stored based on the data structure being used.
• Using concepts like dynamic allocation ensures high efficiency and that the storage
units can be accessed based on requirements in real-time.
Q5. Can you explain the difference between file structure and storage structure?
Answer:
• File Structure: Representation of data into secondary or auxiliary memory say any
device such as a hard disk or pen drives that stores data which remains intact until
manually deleted is known as a file structure representation.
• Storage Structure: In this type, data is stored in the main memory i.e RAM, and is
deleted once the function that uses this data gets completely executed.

The difference is that the storage structure has data stored in the memory of the
computer system, whereas the file structure has the data stored in the auxiliary
memory.
Q6. Describe the types of Data Structures?
Answer:
• Linear Data Structure: A data structure that includes data elements arranged
sequentially or linearly, where each element is connected to its previous and next
nearest elements, is referred to as a linear data structure. Arrays and linked lists are
two examples of linear data structures.
• Non-Linear Data Structure: Non-linear data structures are data structures in
which data elements are not arranged linearly or sequentially. We cannot walk
through all elements in one pass in a non-linear data structure, as in a linear data
structure. Trees and graphs are two examples of non-linear data structures.
Q7. What is a stack data structure? What are the applications of stack?
Answer:
A stack is a data structure that is used to represent the state of an application at a
particular point in time. The stack consists of a series of items that are added to the top
of the stack and then removed from the top. It is a linear data structure that follows a
particular order in which operations are performed.
Following are some applications for stack data structure:
• It acts as temporary storage during recursive operations
• Redo and Undo operations in doc editors
• Reversing a string
• Parenthesis matching
• Postfix to Infix Expressions
• Function calls order
Q8. What are different operations available in stack data structure?
Answer:
• push: This adds an item to the top of the stack. The overflow condition occurs if
the stack is full.
• pop: This removes the top item of the stack. Underflow condition occurs if the
stack is empty.
• top: This returns the top item from the stack.
• isEmpty: This returns true if the stack is empty else false.
• size: This returns the size of the stack.
Q9. What is a queue data structure? What are the applications of queue?
Answer:
A queue is a linear data structure that allows users to store items in a list in a systematic
manner. The items are added to the queue at the rear end until they are full, at which
point
they are removed from the queue from the front. Queues are commonly used in
situations
where the users want to hold items for a long period of time, such as during a checkout
process. A good example of a queue is any queue of customers for a resource where the
first consumer is served first.
some applications of queue data structure:
• Breadth-first search algorithm in graphs
• Operating system: job scheduling operations, Disk scheduling, CPU scheduling
etc.
• Call management in call centres
Q10. What are different operations available in queue data structure?
Answer:
• enqueue: This adds an element to the rear end of the queue. Overflow conditions
occur if the queue is full.
• dequeue: This removes an element from the front end of the queue. Underflow
conditions occur if the queue is empty.
• isEmpty: This returns true if the queue is empty or else false.
• rear: This returns the rear end element without removing it.
• front: This returns the front-end element without removing it.
• size: This returns the size of the queue.
Q11. Differentiate between stack and queue data structure.
Q12. How to implement a queue using stack?
Answer:
A queue can be implemented using two stacks. Let q be the queue and
stack1 and stack2 be the 2 stacks for implementing q. We know that stack supports
push, pop, and peek operations and using these operations, we need to emulate the
operations of the queue - enqueue and dequeue. Hence, queue q can be implemented
in
two methods (Both the methods use auxiliary space complexity of O(n)).
Q13. How do you implement stack using queues?
Answer:
A stack can be implemented using two queues. We know that a queue supports
enqueue
and dequeue operations. Using these operations, we need to develop push, pop
operations.
Q14. What is array data structure? What are the applications of arrays?
Answer:
An array data structure is a data structure that is used to store data in a way that is
efficient and easy to access. It is similar to a list in that it stores data in a sequence.
However, an array data structure differs from a list in that it can hold much more data
than
a list can. An array data structure is created by combining several arrays together. Each
array is then given a unique identifier, and each array’s data is stored in the order in
which
they are created.
Array data structures are commonly used in databases and other computer systems to
store large amounts of data efficiently. They are also useful for storing information that
is
frequently accessed, such as large amounts of text or images.
Q15. What is a linked list data structure? What are the applications for the Linked
list?
Answer:
A linked list can be thought of as a series of linked nodes (or items) that are connected
by
links (or paths). Each link represents an entry into the linked list, and each entry points
to
the next node in the sequence. The order in which nodes are added to the list is
determined by the order in which they are created.
Following are some applications of linked list data structure:
• Stack, Queue, binary trees, and graphs are implemented using linked lists.
• Dynamic management for Operating System memory.
• Round robin scheduling for operating system tasks.
• Forward and backward operation in the browser.
Q16. Difference between Array and Linked List.
Answer:
Q17. What is an asymptotic analysis of an algorithm?
Answer:
Asymptotic analysis of an algorithm defines the run-time performance as per its
mathematical boundations. Asymptotic analysis helps us articulate the best
case(Omega
Notation, Ω), average case(Theta Notation, θ), and worst case(Big Oh Notation, Ο)
performance of an algorithm.
Q18. What is hashmap in data structure?
Answer:
Hashmap is a data structure that uses an implementation of a hash table data structure
which allows access to data in constant time (O(1)) complexity if you have the key.
Q19. What is the requirement for an object to be used as key or value in HashMap?
Answer:
• The key or value object that gets used in the hashmap must
implement equals() and hashcode() method.
• The hash code is used when inserting the key object into the map and the equals
method is used when trying to retrieve a value from the map.
Q20. How does HashMap handle collisions in Java?
Answer:
• The java.util.HashMap class in Java uses the approach of chaining to handle
collisions. In chaining, if the new values with the same key are attempted to be
pushed, then these values are stored in a linked list stored in a bucket of the key as
a chain along with the existing value.
• In the worst-case scenario, it can happen that all keys might have the same
hashcode, which will result in the hash table turning into a linked list. In this case,
searching a value will take O(n) complexity as opposed to O(1) time due to the
nature of the linked list. Hence, care has to be taken while selecting hashing
algorithm.
Q21. What is the time complexity of basic operations get() and put() in HashMap
class?
Answer:
The time complexity is O(1) assuming that the hash function used in the hash map
distributes elements uniformly among the buckets.
Q22. What is binary tree data structure?
Answer:
A binary tree is a data structure that is used to organize data in a way that allows for
efficient retrieval and manipulation. It is a data structure that uses two nodes, called
leaves and nodes, to represent the data. The leaves represent the data and the nodes
represent the relationships between the leaves. Each node has two children, called

siblings, and each child has one parent. The parent is the node that is closest to the root
of the tree. When a node is deleted from the tree, it is deleted from both its child and its
parent.
Q23. What are the applications for binary trees?
Answer:
• It's widely used in computer networks for storing routing table information.
• Decision Trees.
• Expression Evaluation.
• Database indices.
Q24. What is binary search tree data structure?
Answer:
A binary search tree is a data structure that stores items in sorted order. In a binary
search
tree, each node stores a key and a value. The key is used to access the item and the
value is used to determine whether the item is present or not. The key can be any type
of
value such as an integer, floating point number, character string, or even a combination
of
these types. The value can be any type of items such as an integer, floating point
number,
character string, or even a combination of these types. When a node is added to the
tree,
its key is used to access the item stored at that node. When a node is removed from the
tree, its key is used to access the item stored at that node.
Q25. What are the applications for binary search trees?
Answer:
• It is used for indexing and multi-level indexing.
• It is used for implementing various search algorithms.
• It is helpful in organizing a sorted stream of data.
Q26. What are tree traversals?
Answer:
Tree traversal is the process of visiting all the nodes of a tree.
Q27. What is a dequeue data structure and its types?
Answer:
A dequeue can be thought of as an array of items, but with one important difference:
Instead of pushing and popping items off the end to make room, dequeues are
designed
to allow items to be inserted at either end. This property makes dequeues well-suited for
performing tasks such as keeping track of inventory, scheduling tasks, or handling large
amounts of data.
There are two types of dequeue:
• Input Restricted Dequeue: Insertion operations are performed at only one end
while deletion is performed at both ends in the input restricted queue.

• Output Restricted Dequeue: Deletion operations are performed at only one end
while insertion is performed at both ends in the output restricted queue.
Q28. What are some key operations performed on the Dequeue data structure?
Answer:
• insertFront(): This adds an element to the front of the Dequeue.
• insertLast(): This adds an element to the rear of the Dequeue.
• deleteFront(): This deletes an element from the front of the Dequeue.
• deleteLast():This deletes an element from the front of the Dequeue.
• getFront(): This gets an element from the front of the Dequeue.
• getRear(): This gets an element from the rear of the Dequeue.
• isEmpty(): This checks whether Dequeue is empty or not.
• isFull(): This checks whether Dequeue is full or not.
Q29. What is a priority queue?
answer:
Priority Queue is an abstract data type that is similar to a queue in that each element is
assigned a priority value. The order in which elements in a priority queue are served is
determined by their priority (i.e., the order in which they are removed). If the elements
have the same priority, they are served in the order they appear in the queue.
Q30. What are the applications for priority queue?
Answer:
• Used in graph algorithms like Dijkstra, Prim’s Minimum spanning tree etc.
• Huffman code for data compression
• Finding Kth Largest/Smallest element
Q31. Compare different implementations of priority queue.

Q32. What is graph data structure?


Answer:
A graph is a type of non-linear data structure made up of nodes and edges. The nodes
are also known as vertices, and edges are lines or arcs that connect any two nodes in
the graph.
Q33. What is the difference between the Breadth First Search (BFS) and Depth First
Q34. What is AVL tree data structure?
Answer:
AVL trees are height balancing binary search trees named after their inventors Adelson,
Velski, and Landis. The AVL tree compares the heights of the left and right subtrees
and
ensures that the difference is less than one. This distinction is known as the Balance
Factor.
BalanceFactor = height(left-subtree) − height(right-subtree)
Q35. What is a B-tree data structure?
Answer:
The B Tree is a type of m-way tree that is commonly used for disc access. A B-Tree
with
order m can only have m-1 keys and m children. One of the primary reasons for using a
B
tree is its ability to store a large number of keys in a single node as well as large key
values while keeping the tree's height relatively small.
Q36. Define Segment Tree data structure.
Answer:
A segment Tree is a binary tree that is used to store intervals or segments. The
Segment
Tree is made up of nodes that represent intervals. Segment Tree is used when there
are
multiple range queries on an array and changes to array elements.
Q37. What are the applications of trie data structure?
Answer:
some real-time applications for Trie data structure:
• Auto-Complete and Search for Search Engines
• Genome Analysis
• Data Analytics
• Browser History
• Spell Checker
Q38. Define Red-Black Tree .
Answer:
A red-black tree is a Binary tree in which each node has a colour attribute, either red or
black. By comparing the node colours on any simple path from the root to a leaf, red-
black trees ensure that no path is more than twice as long as any other, ensuring that
the
tree is generally balanced.
Q39. Which data structures are used for implementing LRU cache?
Answer:
LRU cache or Least Recently Used cache allows quick identification of an element that
hasn’t been put to use for the longest time by organizing items in order of use. In order
to
achieve this, two data structures are used:
• Queue – This is implemented using a doubly-linked list. The maximum size of the
queue is determined by the cache size, i.e by the total number of available frames.
The least recently used pages will be near the front end of the queue whereas the
most recently used pages will be towards the rear end of the queue.
• Hashmap – Hashmap stores the page number as the key along with the address of
the corresponding queue node as the value.
Q40. What is a heap data structure?
Answer:
Heap is a special tree-based non-linear data structure in which the tree is a complete
binary tree. A binary tree is said to be complete if all levels are completely filled except
possibly the last level and the last level has all elements as left as possible. Heaps are
of
two types:
1. Max-Heap
2. Min-Heap
—————————————————————
Test yourself
Q1. Which of the following is a non-linear data structure?
1. Array
2. Linked list
3. Queue
4. Tree
Q2. Which of the following data structures is linear?
1. Graph
2. AVL tree
3. Red-black tree
4. Stack
Q3. Which data structure is used for implementing recursion?

1. Array
2. Stack
3. Queue
4. Linked list
Q4. Which of the following data structures is preferred in the implementation of a
database system?
1. B tree
2. Binary Search Tree
3. AVL tree
4. B+- tree
Q5. What is the worst-case time complexity of inserting n elements into an empty linked
list that must be kept in sorted order?
1. O(n)
2. O(log n)
3. O(n log n)
4. O(n^2)
Q6. A directed graph is _______ if there is a path from each vertex to every other vertex
in
the graph.
1. Weakly connected
2. Strongly connected
3. Tightly connected
4. Linearly connected
Q7. In circular queue, the value of REAR would be?
1. REAR = REAR + 1
2. REAR = (REAR + 1) % (QUEUE_SIZE+1)
3. REAR = (REAR + 1) % (QUEUE_SIZE)
4. REAR = (REAR - 1) % (QUEUE_SIZE-1)
Q8. Which of the following statement is true?
i) Using singly linked lists and circular list, it is not possible to traverse the list
backwards.
ii) To find the predecessor, it is required to traverse the list from the first node in case of
singly linked list.
1. Only (i)
2. Only (ii)
3. Both (i) and (ii)
4. None of the above
Q9. The binary search method needs no more than ________ comparisons.
1. (Log2 n)+1
2. Log n
3. (Log n)+1
4. Log2n

Q10. What will be the final elements on the stack if the following sequence of operations
are executed?
* Push(a,s);
* Push(b,s);
* Pop(s);
* Push(c,s);
- where a, b, c are the data elements and s is the stack.
1. abc
2. ac
3. acb
4. b
————————————————————
ANSWER:
1. Tree
2. Stack
3. Stack
4. B+- Tree
5. O(n^2)
6. Strongly connected
7. REAR = (REAR + 1) % (QUEUE_SIZE)
8. Both (i) and (ii)
9. (Log2 n)+1
10. ac

pdf 8- OS based question


Q1. Why is the operating system important?
Answer:
OS is the most essential and vital part of a computer without which it is considered
useless. It enables an interface or acts like a link for interaction between computer
software that is installed on OS and users. It also helps to communicate with hardware
and also maintains balance among hardware and CPU. It also provides services to
users
and a platform for programs to run on. It performs all common tasks applications
require.
Q2. What's the main purpose of an OS? What are the different types of OS?
Answer:
The main purpose of an OS is to execute user programs and make it easier for users to
understand and interact with computers as well as run applications. It is specially
designed to ensure that the computer system performs better by managing all
computational activities. It also manages computer memory, processes, and operation
of
all hardware and software.
Types of OS:
• Batched OS (Example: Payroll System, Transactions Process, etc.)
• Multi-Programmed OS (Example: Windows O/S, UNIX O/S, etc.)
• Timesharing OS (Example: Multics, etc.)
• Distributed OS (LOCUS, etc.)
• Real-Time OS (PSOS, VRTX, etc.)
Q3. What are the benefits of a multiprocessor system?
Answer:
• Such systems are used widely nowadays to improve performance in systems that
are running multiple programs concurrently.
• By increasing the number of processors, a greater number of tasks can be
completed in unit time.
• One also gets a considerable increase in throughput and is cost-effective also as all
processors share the same resources.
• It simply improves the reliability of the computer system.
Q4. What is RAID structure in OS?
Answer:
RAID (Redundant Arrays of Independent Disks) is a method used to store data on
Multiple
hard disks therefore it is considered as data storage virtualization technology that
combines multiple hard disks. It simply balances data protection, system performance,
storage space, etc. It is used to improve the overall performance and reliability of data
storage. It also increases the storage capacity of the system and its main purpose is to
achieve data redundancy to reduce data loss
Q5. What is GUI?

Answer:
GUI (Graphical User Interface) is basically a type of user interface that allows users to
use
graphics to interact with OS. GUI is created because it is more user-friendly, less
complex, and easier to understand rather than a command-line interface. Its main goal
is
to increase efficiency and ease of use. Instead of having to memorize commands, users
can just click on a button to simply execute the procedure. Examples of GUI include
Microsoft Windows, macOS, Apple’s iOS, etc.
Q6. What is a Pipe and when it is used?
Answer:
The pipe is generally a connection among two or more processes that are interrelated to
each other. It is a mechanism that is used for inter-process communication using
message passing. One can easily send information such as the output of one program
process to another program process using a pipe. It can be used when two processes
want to communicate one-way i.e., inter-process communication (IPC).
Q7. What are the different kinds of operations that are possible on semaphore?
Answer:
There are basically two atomic operations that are possible:
• Wait()
• Signal()
Q8. What is a bootstrap program in OS?
Answer:
It is generally a program that initializes OS during startup i.e., first code that is executed
whenever computer system startups. OS is loaded through a bootstrapping process or
program commonly known as booting. Overall OS only depends on the bootstrap
program to perform and work correctly. It is fully stored in boot blocks at a fixed location
on the disk. It also locates the kernel and loads it into the main memory after which the
program starts its execution.
Q9. Explain demand paging?
Answer:
Demand paging is a method that loads pages into memory on demand. This method is
mostly used in virtual memory. In this, a page is only brought into memory when a
location on that particular page is referenced during execution.
Q10. What do you mean by RTOS?
Answer:
Real Time Operating System (RTOS) is an operating system that is used for real-time
applications i.e., for those applications where data processing should be done in a fixed
and small measure of time. It performs much better on tasks that are needed to be
executed within a short time. It also takes care of execution, monitoring, and all-
controlling processes. It also occupies less memory and consumes fewer
resources. RTOS is used in Air traffic control systems, Anti-lock Brake Systems, and
Heart pacemakers

Q11. What do you mean by process synchronization?


Answer:
Process synchronization is basically a way to coordinate processes that use shared
resources or data. It is very much essential to ensure synchronized execution of
cooperating processes so that will maintain data consistency. Its main purpose is to share
resources without any interference using mutual exclusion.
Q12. What are the different IPC mechanisms?
Answer:
Different IPC(Interprocess Communication) Mechanisms:
• Pipes
• Message Queuing
• Semaphores
• Socket
• Shared Memory
• Signals
Q14. What do you mean by overlays in OS?
Answer:
Overlays is a programming method that divides processes into pieces so that instructions
that are important and need can be saved in memory. It does not need any type of
support from the OS. It can run programs that are bigger in size than physical memory by
only keeping only important data and instructions that can be needed at any given time.
Q15. Write top 10 examples of OS?
Answer:
Some of the top OS’s that are used mostly are given below:
• MS-Windows
• Ubuntu
• Mac OS
• Fedora
• Solaris
• Free BSD
• Chrome OS
• CentOS
• Debian
• Android
Q16. What is virtual memory?
Answer:
It is a memory management technique feature of OS that creates the illusion to users of a
very large (main) memory. It is simply space where a greater number of programs can be
stored by themselves in the form of pages. It enables us to increase the use of physical
memory by using a disk and also allows us to have memory protection. It can be managed in
two common ways by OS i.e., paging and segmentation. It acts as temporary
storage that can be used along with RAM for computer processes.
Q17. What is thread in OS?
Answer:
Thread is a path of execution that is composed of a program counter, thread id, stack,
and set of registers within the process. It is a basic unit of CPU utilization that makes
communication more effective and efficient, enables utilization of multiprocessor
architectures to a greater scale and greater efficiency, and reduces the time required in
context switching. It simply provides a way to improve and increase the performance of
applications through parallelism.
Threads are sometimes called lightweight processes because they have their own stack
but can access shared data.
Q18. What is a process?
Answer:
The process is basically a program that is currently under execution. The main function
of
an OS is to manage and handle all of these processes. When a program is loaded into
the
memory and it becomes a process, it can be divided into four sections ─ stack, heap,
text, and data.
Q19. What are the different states of a process?
Answer:
• New State: In this state, a process is just created.
• Running: In this state, the CPU starts working on the process’s instructions.
• Waiting: In this state, the process cannot run because it just waits for some event
to occur
• Ready: In this state, the process has all resources available that are required to run
but it waits to get assigned to a processor because CPUs are not working currently
on instructions passed by the process.
• Terminate: In this state, the process is completed I.e., the process has finished
execution.
Q20. What do you mean by FCFS?
Answer:
FCFS (First Come First Serve) is a type of OS scheduling algorithm that executes
processes in the same order in which processes arrive. In simple words, the process
that
arrives first will be executed first. It is non-preemptive in nature. FCFS scheduling may
cause the problem of starvation if the burst time of the first process is the longest
among
all the jobs. Burst time here means the time that is required in milliseconds by the
process
for its execution. It is also considered the easiest and simplest OS scheduling algorithm
as compared to others. Implementation of FCFS is generally managed with help of the
FIFO (First In First Out) queue.
Q21. What is Reentrancy?
Answer:
Reentrant is simply a function in which various clients can use and shares a single copy
of a program during a similar period. This concept is generally associated with OS code
and does not deal with concurrency. It has two major functions:
• Program code cannot change or modify itself.
• Local data for every client process needs to be stored in different disks.
Q22. What is a Scheduling Algorithm?
Answer:
A scheduling algorithm is a process that is used to improve efficiency by utilizing
maximum CPU and providing minimum waiting time to tasks. It simply deals with the
problem of deciding which of outstanding requests is to be allocated resources. Its main
aim is to reduce resource starvation and to ensure fairness amongst parties that are
utilizing the resources. In simple words, it is used to allocate resources among various
competing tasks.
Q23. What is the difference between paging and segmentation?
Q24. What is paging and segmentation?
Answer:
Paging: It is generally a memory management technique that allows OS to retrieve
processes from secondary storage into main memory. It is a non-contiguous allocation
technique that divides each process in the form of pages.
Segmentation: It is generally a memory management technique that divides processes
into modules and parts of different sizes. These parts and modules are known as
segments that can be allocated to process.
Q25. What is thrashing in OS?
Answer:
It is generally a situation where the CPU performs less productive work and more
swapping or paging work. It spends more time swapping or paging activities rather than
its execution. By evaluating the level of CPU utilization, a system can detect thrashing.
It
occurs when the process does not have enough pages due to which the page-fault rate
is
increased. It inhibits much application-level processing that causes computer
performance to degrade or collapse.
Q26. What is the main objective of multiprogramming?
Answer:
It refers to the ability to execute or perform more than one program on a single
processor
machine. This technique was introduced to overcome the problem of underutilization of
CPU and main memory. In simple words, it is the coordination of execution of various
programs simultaneously on a single processor (CPU). The main objective of
multiprogramming is to have at least some processes running at all times. It simply
improves the utilization of the CPU as it organizes many jobs where the CPU always
has one to execute.
Q27. What do you mean by asymmetric clustering?
Answer:
Asymmetric Clustering is generally a system in which one of the nodes among all nodes
is
in hot standby mode whereas the rest of all nodes run different applications. It simply
uses whole or entire hardware resources therefore it is considered a more reliable
system
as compared to others.
Q28. What is the difference between multitasking and multiprocessing OS?
Q29. What do you mean by Sockets in OS?
Answer: The socket in OS is generally referred to as an endpoint for IPC (Interprocess
Communication). Here, the endpoint is referred to as a combination of an IP address
and port number. Sockets are used to make it easy for software developers to create
network-enabled programs. It also allows communication or exchange of information
between two different processes on the same or different machines. It is mostly used in
client-server-based systems.
Q30. What are the different types of socket?
Answer:
There are basically four types of sockets as given below:
• Stream Sockets
• Datagram Sockets
• Sequenced Packet Sockets
• Raw Sockets
Q31.Explain zombie process?
Answer;
Zombie process, referred to as a defunct process, is basically a process that is
terminated or completed but the whole process control block is not cleaned up from the
main memory because it still has an entry in the process table to report to its parent
process. It does not consume any of the resources and is dead, but it still exists. It also
shows that resources are held by process and are not free.
Q32. What do you mean by cascading termination?
Answer:
Cascading termination is a process termination in which if the parent process is exiting
or
terminating then the children process will also get terminated. It does not allow the child
to continue processing as its parent process terminates. It is generally initiated by OS.
Q33. What is starvation and aging in OS?
Answer:
Starvation: It is generally a problem that usually occurs when a process has not been
able to get the required resources it needs for progress with its execution for a long
period of time. In this condition, low priority processes get blocked and only high priority
processes proceed towards completion because of which low priority processes suffer
from lack of resources.
Aging: It is a technique that is used to overcome the situation or problem of starvation. It
simply increases the priority of processes that wait in the system for resources for a
long
period of time. It is considered the best technique to resolve the problem of starvation
as
it adds an aging factor to the priority of each and every request by various processes for
resources. It also ensures that low-level queue jobs or processes complete their
execution.
Q34. What do you mean by Semaphore in OS?
Answer:

Semaphore is a signaling mechanism. It only holds one positive integer value. It is


simply
used to solve the problem or issue of critical sections in the synchronization process by
using two atomic operations i.e., wait() and signal().
Q35. What is Kernel and write its main functions?
Answer:
The kernel is basically a computer program usually considered as a central component
or
module of OS. It is responsible for handling, managing, and controlling all operations of
computer systems and hardware. Whenever the system starts, the kernel is loaded first
and remains in the main memory. It also acts as an interface between user applications
and hardware.
Functions of Kernel:
• It is responsible for managing all computer resources such as CPU, memory, files,
processes, etc.
• It facilitates or initiates the interaction between components of hardware and
software.
• It manages RAM memory so that all running processes and programs can work
effectively and efficiently.
• It also controls and manages all primary tasks of the OS as well as manages
access and use of various peripherals connected to the computer.
• It schedules the work done by the CPU so that the work of each user is executed
as efficiently as possible.
Q36. What are different types of Kernel?
Answer:
There are basically five types of Kernels as given below:
• Monolithic Kernel
• MicroKernel
• Hybrid Kernel
• Nano Kernel
• Exo Kernel
Q37. Write difference between micro kernel and monolithic kernel?
Answer:
MicroKernel: It is a minimal OS that executes only important functions of OS. It only
contains a near-minimum number of features and functions that are required to
implement
OS.
Example: QNX, Mac OS X, K42, etc.
Monolithic Kernel: It is an OS architecture that supports all basic features of computer
components such as resource management, memory, file, etc.
Example: Solaris, DOS, OpenVMS, Linux, etc.
Q38. What is SMP (Symmetric Multiprocessing)?

Answer:
SMP is generally referred to as computer architecture in which the processing of
programs is done by multiple processors that share a common OS and memory. SMP is
very much required if you want to take advantage of multiprocessor hardware. It simply
enables any processor to work on any of the tasks no matter where data or resources
for
that particular task are located in memory. These systems are more reliable than single-
processor systems.
Q39. What is a time-sharing system?
Answer:
It is a system that allows more than one user to access the resources of a particular
system in many locations. In simple words, it performs multiple tasks on a single
processor or CPU. As the name suggests, it means to share time into multiple slots in
several processes. It also allows different users from different locations to use a
particular
computer system at the same time therefore it is considered one of the important types
of
OS.
Q40. What is Context Switching?
Answer:
Context switching is basically a process of saving the context of one process and
loading
the context of another process. It is one of the cost-effective and time-saving measures
executed by CPU the because it allows multiple processes to share a single CPU.
Therefore, it is considered an important part of a modern OS. This technique is used by
OS to switch a process from one state to another i.e., from running state to ready state.
It
also allows a single CPU to handle and control various different processes or threads
without even the need for additional resources.
Q41. What is difference between Kernel and OS?
Q43. What are various sections of the process?
Answer:
There are basically four sections in the process as given below:
• Stack: It is used for local variables and returns addresses.
• Heap: It is used for dynamic memory allocation.
• Data: It stores global and static variables.
• Code or text: It comprises compiled program code.
Q44. What is a deadlock in OS?
Answer:
Deadlock is a situation where a set of processes are blocked as each process is holding
resources and waits to acquire resources held by another process. In this situation, two
or
more processes simply try to execute simultaneously and wait for each to finish their
execution because they are dependent on each other. We can see a hand problem in
our
system whenever a deadlock occurs in a program. It is one of the common problems
you
can see in multiprocessing.
Q45. What are the necessary conditions for a deadlock?
Answer:
There are four necessary conditions for deadlock as given below:
• Mutual Exclusion
• Hold and Wait
• No Pre-emption
• Circular Wait or Resource Wait
Q46. What do you mean by Belady’s Anomaly?
Answer:In the Operating System, process data is loaded in fixed-sized chunks and each
chunk is referred to as a page. The processor loads these pages in the fixed-sized
chunks of
memory called frames. Belady’s Anomaly is a phenomenon in which if we increase the
number of frames in memory, then the number of page faults also increases. It is
generally experienced when we use FIFO (First in First out) page replacement
algorithm.
Q47. What is spooling in OS?
Answer:
Spooling simply stands for Simultaneous peripheral operations online. It is referred to as
putting data of various I/O jobs in a buffer. Here, buffer means a special area in memory
or hard disk that can be accessible to an I/O device. It is used for mediation between a
computer application and a slow peripheral. It is very useful and important because
devices access or acquire data at different rates. This operation also uses disk as a
very
large buffer and is capable of overlapping I/O operations for one task with processor
operations for another task.
Q48. What is a process?
Answer:
Process is a program that is currently under execution by one or more threads. It is a
very important part of the modern-day OS.
Q49. What is a thread?
Answer:
Thread is a path of execution that is composed of the program counter, thread id, stack,
and set of registers within the process.
Q50. What is a kernel?
Answer:
Kernel is a system program that controls all programs running on the computer. The
kernel is basically a bridge between the software and hardware of the system.
Q51. What happens if a non-recursive mutex is locked more than once?
Answer:
Deadlock. If a thread that had already locked a mutex, tries to lock the mutex again, it
will
enter into the waiting list of that mutex, which results in a deadlock. It is because no
other
thread can unlock the mutex. An operating system implementer can exercise care in
identifying the owner of the mutex and return it if it is already locked by the same thread
to prevent deadlocks.
Q52. What are the different scheduling algorithms?
Answer:
First-Come, First-Served (FCFS) Scheduling.
Shortest-Job-Next (SJN) Scheduling.

Priority Scheduling.
Shortest Remaining Time.
Round Robin(RR) Scheduling.
Multiple-Level Queues Scheduling.
Q53. What is the time-sharing system?
Answer:
Time-sharing is a logical extension of multiprogramming. The CPU performs many tasks
by switches that are so frequent that the user can interact with each program while it is
running. A time-shared operating system allows multiple users to share computers
simultaneously.
Q54. What is Banker’s algorithm?
Answer:
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that
tests for safety by simulating the allocation for predetermined maximum possible
amounts of all resources, then makes an “s-state” check to test for possible activities,
before deciding whether allocation should be allowed to continue.
Q55. State the main difference between logical and physical address space?
Q56. How does dynamic loading aid in better memory space utilization?
ANSWER:
With dynamic loading, a routine is not loaded until it is called. This method is especially
useful when large amounts of code are needed in order to handle infrequently occurring
cases such as error routines.
Q57. What is fragmentation?
ANSWER:
Processes are stored and remove from memory, which makes free memory space,
which
is too little to even consider utilizing by different processes. Suppose, that process is not
ready to dispense to memory blocks since its little size and memory hinder consistently
stay unused is called fragmentation. This kind of issue occurs during a dynamic memory
allotment framework when free blocks are small, so it can’t satisfy any request.
Q58. What is the basic function of paging?
ANSWER:
Paging is a method or technique which is used for non-contiguous memory allocation. It
is a fixed-size partitioning theme (scheme). In paging, both main memory and
secondary
memory are divided into equal fixed-size partitions. The partitions of the secondary
memory area unit and the main memory area unit are known as pages and frames
respectively.
Paging is a memory management method accustomed fetch processes from the
secondary memory into the main memory in the form of pages. in paging, each process
is
split into parts wherever the size of every part is the same as the page size. The size of
the last half could also be but the page size. The pages of the process area unit hold on
within the frames of main memory relying upon their accessibility
Q59. How does swapping result in better memory management?
ANSWER:
Swapping is a simple memory/process management technique used by the operating
system(os) to increase the utilization of the processor by moving some blocked
processes
from the main memory to the secondary memory thus forming a queue of the
temporarily
suspended processes and the execution continues with the newly arrived process.
During
regular intervals that are set by the operating system, processes can be copied from the
main memory to a backing store, and then copied back later. Swapping allows more
processes to be run that can fit into memory at one time
Access The user can
use the logical
address to
access the
physical
address.
The user can
indirectly
access physical
address but not
directly.
Q60. Write a name of classic synchronization problems?
ANSWER:
• Bounded-buffer
• Readers-writers
• Dining philosophers
• Sleeping barber
————————————————————————
TEST YOURSELF
Q1. Which of the following is not considered as an OS?
1. Windows XP
2. LINUX
3. Fedora
4. Mac OS X
Q2. What is the use of a banker's algorithm?
1. RECTIFY DEADLOCK
2. SOLVE DEADLOCK
3. PREVENT DEADLOCK
4. ALL OF THE ABOVE
Q3. _____________ is not an approach to Handling Deadlock.
1. Detect and recover
2. Deadlock avoidance
3. Virtual memory
4. Deadlock prevention
Q4. Which of the following programs runs just after booting the computer and loading
GUI?
1. Windows explorer
2. File manager
3. Authentication
4. Desktop manager
Q5. Which of the following usually provides the interface to get access to the services of
OS?
1. System call
2. Library
3. API
4. All of the above
Q6. Name the program that runs first after booting the computer as well as loading the
GUI.
1. Windows explorer

2. File manager
3. Authentication
4. None of the above
Q7. Which of the following is the main function of the Command Interpreter?
1. To get and execute next user-specified command
2. To handle and maintain all files in OS
3. To provide an interface between application program and API
4. None of the above
Q8. What does the OS create from a physical computer?
1. Virtual Computer
2. Virtual Space
3. Virtual Device
4. None of the above
Q9. In which of the following components is paging implemented?
1. Software
2. Operating System
3. Hardware
4. None of the above
Q10. What is the use of the Fence Register?
1. Disk Protection
2. CPU Protection
3. Memory Protection
4. None of the above
————————————————————
Answer:
1. Linux
2. Prevent deadlock
3. Virtual memory
4. Authentication
5. All of the above
6. Authentication
7. To get and execute next user-specified command
8. Virtual computer
9. Hardware
10. Memory protection

Pdf 7 - dbms based questions


Q1. What is DBMS and what is its utility?
Answer:
DBMS stands for Database Management System, is a set of applications or programs
that enable users to create and maintain a database. DBMS provides a tool or an
interface for performing various operations such as inserting, deleting, updating, etc.
into
a database. It is software that enables the storage of data more compactly and securely
as compared to a file-based system. A DBMS system helps a user to overcome
problems
like data inconsistency, data redundancy, etc. in a database and makes it more
convenient and organized to use it.
Q2. Explain RDBMS with examples.
Answer:
RDBMS stands for Relational Database Management System and was introduced in
the 1970s to access and store data more efficiently than DBMS. RDBMS stores data in
the form of tables as compared to DBMS which stores data as files. Storing data as
rows
and columns makes it easier to locate specific values in the database and makes it
more
efficient as compared to DBMS.
Examples of popular RDBMS systems are MySQL, Oracle DB, etc.
Q3. What is a Database?
Answer:
A Database is an organized, consistent, and logical collection of data that can easily be
updated, accessed, and managed. Database mostly contains sets of tables or objects
(anything created using create command is a database object) which consist of records
and fields. A tuple or a row represents a single entry in a table. An attribute or a column
represents the basic units of data storage, which contain information about a particular
aspect of the table.
Q4. Mention the issues with traditional file-based systems that make DBMS a better
choice?
Answer:
The absence of indexing in a traditional file-based system leaves us with the only option
of scanning the full page and hence making the access of content tedious and super
slow. The other issue is redundancy and inconsistency as files have many duplicate and
redundant data and changing one of them makes all of them inconsistent. Accessing
data
is harder in traditional file-based systems because data is unorganized in them.
Another issue is the lack of concurrency control, which leads to one operation locking
the
entire page, as compared to DBMS where multiple operations can work on a single file
simultaneously.
Integrity check, data isolation, atomicity, security, etc. are some other issues with
traditional file-based systems for which DBMSs have provided some good solutions.

Q5. Are NULL values in a database the same as that of blank space or zero?
Answer:
No, a NULL value is very different from that of zero and blank space as it represents a
value that is assigned, unknown, unavailable, or not applicable as compared to blank
space which represents a character and zero represents a number.
Example: NULL value in “number_of_courses” taken by a student represents that its
value
is unknown whereas 0 in it means that the student hasn’t taken any courses
.
Q6. Explain different levels of data abstraction in a DBMS.
Answer:
The process of hiding irrelevant details from users is known as data abstraction. Data
abstraction can be divided into 3 levels:
• Physical Level: it is the lowest level and is managed by DBMS. This level consists
of data storage descriptions and the details of this level are typically hidden from
system admins, developers, and users.
• Conceptual or Logical level: it is the level on which developers and system
admins work and it determines what data is stored in the database and what is the
relationship between the data points.
• External or View level: it is the level that describes only part of the database and
hides the details of the table schema and its physical storage from the users. The
result of a query is an example of View level data abstraction. A view is a virtual
table created by selecting fields from one or more tables present in the database.
Q7. Explain the difference between intension and extension in a database.
answer:
• Intension: Intension or popularly known as database schema is used to define the
description of the database and is specified during the design of the database and
mostly remains unchanged.
• Extension: Extension on the other hand is the measure of the number of tuples
present in the database at any given point in time. The extension of a database is
also referred to as the snapshot of the database and its value keeps changing as
and when the tuples are created, updated, or destroyed in a database.
Q8. Explain the difference between the DELETE and TRUNCATE command in a
DBMS.
Answer:
DELETE command: this command is needed to delete rows from a table based on the
condition provided by the WHERE clause.
TRUNCATE command: this command is needed to remove complete data from a table
in a database. It is like a DELETE command which has no WHERE clause.

Q9. What is a lock? Explain the major difference between a shared lock and an
exclusive lock during a transaction in a database.
Answer:
A database lock is a mechanism to protect a shared piece of data from getting updated
by two or more database users at the same time. When a single database user or
session
has acquired a lock then no other database user or session can modify that data until
the
lock is released.
• Shared Lock: A shared lock is required for reading a data item and many
transactions may hold a lock on the same data item in a shared lock. Multiple
transactions are allowed to read the data items in a shared lock.
• Exclusive lock: An exclusive lock is a lock on any transaction that is about to
perform a write operation. This type of lock doesn’t allow more than one
transaction and hence prevents any inconsistency in the database.
Q10. What is meant by normalization and denormalization?
Answer:
Normalization is a process of reducing redundancy by organizing the data into multiple
tables. Normalization leads to better usage of disk spaces and makes it easier to
maintain
the integrity of the database.
Denormalization is the reverse process of normalization as it combines the tables which
have been normalized into a single table so that data retrieval becomes faster. JOIN
operation allows us to create a denormalized form of the data by reversing the
normalization.
Q11. Explain the difference between a 2-tier and 3-tier architecture in a DBMS.
Answer:
The 2-tier architecture refers to the client-server architecture in which applications at the
client end directly communicate with the database at the server end without any
middleware involved.
The 3-tier architecture contains another layer between the client and the server to
provide GUI to the users and make the system much more secure and accessible. In
this
type of architecture, the application present on the client end interacts with an
application
on the server end which further communicates with the database system.
Q12. What are the advantages of DBMS?
Answer:
• Redundancy control
• Restriction for unauthorized access
• Provides multiple user interfaces
• Provides backup and recovery
• Enforces integrity constraints
• Ensure data consistency
• Easy accessibility
• Easy data extraction and data processing due to the use of queries

Q13. What is a checkpoint in DBMS?


Answer:
The Checkpoint is a type of mechanism where all the previous logs are removed from
the
system and permanently stored in the storage disk.
Q14. What do you mean by transparent DBMS?
Answer:
The transparent DBMS is a type of DBMS which keeps its physical structure hidden
from
users. Physical structure or physical storage structure implies to the memory manager
of
the DBMS, and it describes how the data stored on disk.
Q15. What is DDL (Data Definition Language)?
Answer:
Data Definition Language (DDL) is a standard for commands which defines the different
structures in a database. Most commonly DDL statements are CREATE, ALTER, and
DROP. These commands are used for updating data into the database.
Q16. What is DML (Data Manipulation Language)?
Answer:
Data Manipulation Language (DML) is a language that enables the user to access or
manipulate data as organized by the appropriate data model. For example- SELECT,
UPDATE, INSERT, DELETE.
There is two type of DML:
Procedural DML or Low level DML: It requires a user to specify what data are needed
and how to get those data.
Non-Procedural DML or High level DML:It requires a user to specify what data are
needed without specifying how to get those data.
Q17. What do you understand by query optimization?
Answer:
The term query optimization specifies an efficient execution plan for evaluating a query
that has the least estimated cost. The concept of query optimization came into the
frame
when there were a number of methods, and algorithms existed for the same task then
the
question arose that which one is more efficient and the process of determining the
efficient way is known as query optimization.
Q18. What is SQL and where is it used?
Answer:

Structured Query Language is the core of the relational database which is used for
accessing and managing the databases. This language is used to manipulate and
retrieve
data from a structured data format in the form of tables and holds relationships between
those tables. So, in layman terms, you can use SQL to communicate with the database.
Q19. What do you understand by sub-queries in SQL?
Answer:
A subquery is a query inside another query where a query is defined to retrieve data or
information back from the database. In a subquery, the outer query is called as the main
query whereas the inner query is called subquery. Subqueries are always executed first
and the result of the subquery is passed on to the main query. It can be nested inside a
SELECT, UPDATE or any other query. A subquery can also use any comparison
operators
such as >,< or =.
Q20. Mention the differences between UNION and UNION ALL
Answer:
Q21. What do you understand by CLAUSE in SQL?
Answer:
CLAUSE in SQL is used to limit the result set by mentioning a condition to the query.
So,
you can use a CLAUSE to filter rows from the entire set of records.
Example: WHERE HAVING clause.
Q22. Mention the differences between HAVING and WHERE clause?

Q23. How can you perform pattern matching in SQL?


Answer:
You can perform pattern matching in SQL by using the LIKE operator. With the LIKE
operator, you can use the following symbols:
1. %(Percentage sign) – To match zero or more characters.
2. _ (Underscore) –To match exactly one character._’
Example:
SELECT * FROM Customers WHERE CustomerName LIKE ‘s%’
SELECT * FROM Customers WHERE CustomerName like ‘xyz
Q24. What does initial in SQL do?
Answer:
This function returns the string with the first letter in uppercase and the rest of the letters
in lowercase.
Syntax: INITCAP(‘string’)
Q25. What are joins in SQL and what are the different types of joins?
Answer:
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them. It is used to merge two tables or retrieve data from there. There
are 4 joins in SQL namely:
• Inner Join
• Right Join
• Left Join
• Full Join
Q26. Write a query to create a duplicate table with and without data present?
Answer:
CREATE TABLE DuplicateCustomer AS SELECT * FROM Customers;

Q27. Mention a query to calculate the even and odd records from a table
Answer:
Even records
SELECT CustomerID FROM (SELECT rowno, CustomerID from Customers) where
mod(rowno,2)=0;
Odd records
SELECT CustomerID FROM (SELECT rowno, CustomerID from Customers) where
mod(rowno,2)=1;
Q28. Write a query to remove duplicate rows from a table?
Note: To remove duplicate rows from a table, you have to initially select the duplicate
rows from the table without using the DISTINCT keyword.
SELECT CustomerNumber FROM Customers WHERE ROWID (SELECT MAX (rowid)
FROM Customers C WHERE CustomerNumber = C.CustomerNumber);
DELETE FROM Customers WHERE ROWID(SELECT MAX (rowid) FROM Customers
C
WHERE CustomerNumber = C.CustomerNumber);
Q29. Mention a query to add email validation to your database
Answer:
SELECT Email FROM Customers WHERE NOT REGEXP_LIKE(Email, &amp;lsquo;[A-
Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}&amp;rsquo;, &amp;lsquo;i&amp;rsquo;);
Q30. What is an Extension of entity type?
Answer:
An extension of an entity type is specified as a collection of entities of a particular entity
type that are grouped into an entity set.
Q31. What is Join?
Answer:
The Join operation is one of the most useful activities in relational algebra. It is most
commonly used way to combine information from two or more relations. A Join is
always
performed on the basis of the same or related column. Most complex queries of SQL
involve JOIN command.
Q32. What is stored procedure?
Answer:
A stored procedure is a group of SQL statements that have been created and stored in
the database. The stored procedure increases the reusability as here the code or the
procedure is stored into the system and used again and again that makes the work
easy,
takes less time in processing and decreases the complexity of the system. So, if you
have

a code which you need to use again and again then save that code and call that code
whenever it is required.
Q33. How do you communicate with an RDBMS?
Answer:
You have to use Structured Query Language (SQL) to communicate with the RDBMS.
Using queries of SQL, we can give the input to the database and then after processing
of
the queries database will provide us the required output.
Q34. What is the 3-Tier architecture?
Answer:
The 3-Tier architecture contains another layer between the client and server.
Introduction
of 3-tier architecture is for the ease of the users as it provides the GUI, which, make the
system secure and much more accessible. In this architecture, the application on the
client-end interacts with an application on the server which further communicates with
the database system.
Q35. What is BCNF?
Answer:
• BCNF: BCNF stands for Boyce-Codd Normal Form and is an advanced form of
3NF. It is also referred to as 3.5NF for the same reason. A table to be in its BCNF
normal form should satisfy the following conditions:
• The table should be in its 3NF i.e. satisfy all the conditions of 3NF.
• For every functional dependency of any attribute A on B
(A->B), A should be the super key of the table. It simply implies that A can’t be a
non-prime attribute if B is a prime attribute.
Q36. What is a candidate key?
Answer;
The candidate key represents a set of properties that can uniquely identify a table. Each
table may have multiple candidate keys. One key amongst all candidate keys can be
chosen as a primary key. In the below example since studentId and firstName can be
considered as a Candidate Key since they can uniquely identify every tuple.
Q37. What is a super key?
Answer:
The super key defines a set of attributes that can uniquely identify a tuple. Candidate
key
and primary key are subsets of the super key, in other words, the super key is their
superset.
Q38. What is a primary key?
Answer:

The primary key defines a set of attributes that are used to uniquely identify every tuple.
In the below example studentId and firstName are candidate keys and any one of them
can be chosen as a Primary Key. In the given example studentId is chosen as the
primary
key for the student table.
Q39. What is a unique key?
Answer:
The unique key is very similar to the primary key except that primary keys don’t allow
NULL values in the column but unique keys allow them. So essentially unique keys are
primary keys with NULL values.
Q40. What is an alternate key?
Answer:
All the candidate keys which are not chosen as primary keys are considered as
alternate
Keys. In the below example, firstname and lastname are alternate keys in the database.
Q41. What is a foreign key?
Answer:
The foreign key defines an attribute that can only take the values present in one table
common to the attribute present in another table. In the below example courseId from
the
Student table is a foreign key to the Course table, as both, the tables contain courseId
as
one of their attributes.
Q42. What is a composite key?
Answer:
A composite key refers to a combination of two or more columns that can uniquely
identify each tuple in a table. In the below example the studentId and firstname can be
grouped to uniquely identify every tuple in the table.
——————————————————————
TEST YOURSELF
Q1. An entity set is represented by what in an E-R diagram?
1. Circle
2. Rectangle
3. Diamond
4. Ellipse
Q2. A record in a relational DBMS is also known as:
1. Tuple
2. Attribute
3. Relation
4. Criteria
Q3. What does ODBC in a database stand for:
1. Oral database connection
2. Oracle database connection
3. Open database connectivity
4. Oracle database connectivity
Q4. Which of the following represents a one-to-many relationship?
1. One teacher many students
2. One teacher one class
3. Many teachers one class
4. Many teacher one student
Q5. Which of the following contains information about the data stored in a DBMS?
1. Meta data
2. Directory
3. Sub data
4. Warehouse
Q6. Which of the following does DBA stand for?
1. Database administrator
2. Data administrator
3. Database attribute
4. Data analysis
Q7. In a DBMS, TCL means
1. Transaction control language
2. Transmission central language
3. Transaction central language
4. None of the above
Q8. Data Manipulation Language (DML) is not to
1. Create information table in the Database
2. Insertion of new information into the Database
3. Deletion of information in the Database
4. Modification of information in the Database
Q9. The minimal set of super key is called
1. Primary key
2. Secondary key
3. Candidate key
4. Foreign key
Q10. A data dictionary doesn't provide information about:
1. Where data is located
2. The size of the disk storage device
3. It allows a many-to-many relationship

4. It is conceptually simple
————————————————————
Answers:
1. Rectangle
2. Tuple
3. Open database connectivity
4. one teacher many students
5. meta data
6. Database administrator
7. Transaction control language
8. Create information table in the Database
9. Candidate key
10. The size of the disk storage device

Pdf 6 - java based question


Q1. Why is Java a platform independent language?
Answer:
Java language was developed in such a way that it does not depend on any
hardware or software due to the fact that the compiler compiles the code and
then converts it to platform-independent byte code which can be run on
multiple systems.
The only condition to run that byte code is for the machine to have a runtime
environment (JRE) installed in it
Q2. Why is Java not a pure object oriented language?
Answer:
Java supports primitive data types - byte, boolean, char, short, int, float, long,
and double and hence it is not a pure object oriented language.
Q3. Difference between Heap and Stack Memory in java. And how java
utilizes this.
Answer:
Stack memory is the portion of memory that was assigned to every individual
program. And it was fixed. On the other hand, Heap memory is the portion that
was not allocated to the java program but it will be available for use by the java
program when it is required, mostly during the runtime of the program.
Java Utilizes this memory as -
When we write a java program then all the variables, methods, etc are stored in
the stack memory.
And when we create any object in the java program then that object was
created in the heap memory. And it was referenced from the stack memory.
Q4. Can java be said to be the complete object-oriented programming
language?
Answer:
Java is not a pure object-oriented programming language, because it has direct
access to primitive data types. And these primitive data types don't directly
belong to the Integer classes.
Q5. How is Java different from C++?
Answer:
C++ is only a compiled language, whereas Java is compiled as well as an
interpreted language.
Java programs are machine-independent whereas a c++ program can run only
in the machine in which it is compiled.

C++ allows users to use pointers in the program. Whereas java doesn’t allow it.
Java internally uses pointers.
C++ supports the concept of Multiple inheritances whereas Java doesn't
support this. And it is due to avoiding the complexity of name ambiguity that
causes the diamond problem.
Q6. Pointers are used in C/ C++. Why does Java not make use of
pointers?
Answer:
Pointers are quite complicated and unsafe to use by beginner programmers.
Java focuses on code simplicity, and the usage of pointers can make it
challenging. Pointer utilization can also cause potential errors. Moreover,
security is also compromised if pointers are used because the users can
directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in
Java. Moreover, the usage of pointers can make the procedure of garbage
collection quite slow and erroneous. Java makes use of references as these
cannot be manipulated, unlike pointers.
Q7. What do you understand by an instance variable and a local
variable?
Answer:
Instance variables are those variables that are accessible by all the methods
in the class. They are declared outside the methods and inside the class. These
variables describe the properties of an object and remain bound to it at any
cost.
All the objects of the class will have their copy of the variables for utilization. If
any modification is done on these variables, then only that instance will be
impacted by it, and all other class instances continue to remain unaffected.
Local variables are those variables present within a block, function, or
constructor and can be accessed only inside them. The utilization of the
variable is restricted to the block scope. Whenever a local variable is declared
inside a method, the other class methods don’t have any knowledge about the
local variable.
Q8. What are the default values assigned to variables and instances in
java?
Answer:
There are no default values assigned to the variables in java. We need to
initialize the value before using it. Otherwise, it will throw a compilation error
of (Variable might not be initialized).
But for instance, if we create the object, then the default value will be
initialized by the default constructor depending on the data type.
If it is a reference, then it will be assigned to null.
If it is numeric, then it will assign to 0.
If it is a boolean, then it will be assigned to false. Etc.

Q9. What do you mean by data encapsulation?


Answer:
Data Encapsulation is an Object-Oriented Programming concept of hiding the
data attributes and their behaviors in a single unit.
It helps developers to follow modularity while developing software by ensuring
that each object is independent of other objects by having its own methods,
attributes, and functionalities.
It is used for the security of the private properties of an object and hence
serves the purpose of data hiding.
Q10. Tell us something about JIT compiler.
Answer:
JIT stands for Just-In-Time and it is used for improving the performance during
run time. It does the task of compiling parts of byte code having similar
functionality at the same time thereby reducing the amount of compilation
time for the code to run.
The compiler is nothing but a translator of source code to machine-executable
code. But what is special about the JIT compiler? Let us see how it works:
First, the Java source code (.java) conversion to byte code (.class) occurs with
the help of the javac compiler.
Then, the .class files are loaded at run time by JVM and with the help of an
interpreter, these are converted to machine understandable code.
JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes
the method calls in the .class files and compiles them to get more efficient
and native code. It also ensures that the prioritized method calls are
optimized.
Once the above step is done, the JVM executes the optimized code directly
instead of interpreting the code again. This increases the performance and
speed of the execution.
Q11. Can you tell the difference between equals() method and equality
operator (==) in Java?
Answer:
equals()equals() ====
This is a methodThis is a method
defined in thedefined in the
It is a binaryIt is a binary
operator in Java.operator in Java.
This method isThis method is
used forused for
This operator isThis operator is
used forused for
Q12. How is an infinite loop declared in Java?
Answer:
Infinite loops are those loops that run infinitely without any breaking
conditions. Some examples of consciously declaring infinite loop is:
Using For Loop:
for (;;)
{
// Business logic
// Any break logic

}
Using while loop:
while(true){
// Business logic
// Any break logic
}
Using do-while loop:
do{
// Business logic
// Any break logic
}while(true);
Q13. Briefly explain the concept of constructor overloading
Answer:
Constructor overloading is the process of creating multiple constructors in the
class consisting of the same name with a difference in the constructor
parameters. Depending upon the number of parameters and their
corresponding types, distinguishing of the different types of constructors is
done by the compiler.
Q14. Define Copy constructor in java.
Answer:
Copy Constructor is the constructor used when we want to initialize the value
to the new object from the old object of the same class.
Q15. Can the main method be Overloaded?
Answer:
Yes, It is possible to overload the main method. We can create as many
overloaded main methods we want. However, JVM has a predefined calling
method that JVM will only call the main method with the definition of -
public static void main(string[] args)
Q16. A single try block and multiple catch blocks can co-exist in a Java
Program. Explain.
Answer:
Yes, multiple catch blocks can exist but specific approaches should come prior
to the general approach because only the first catch block satisfying the catch
condition is executed.
Q17. Explain the use of final keyword in variable, method and class.
Answer:
In Java, the final keyword is used as defining something as constant /final and
represents the non-access modifier.
final variable:
When a variable is declared as final in Java, the value can’t be modified once it
has been assigned.
If any value has not been assigned to that variable, then it can be assigned
only by the constructor of the class.
final method:
A method declared as final cannot be overridden by its children's classes.
A constructor cannot be marked as final because whenever a class is inherited,
the constructors are not inherited. Hence, marking it final doesn't make
sense. Java throws compilation error saying - modifier final not allowed here
final class:
No classes can be inherited from the class declared as final. But that final class
can extend other classes for its usage.

Q18. Do final, finally and finalize keywords have the same function?
Answer:
All three keywords have their own utility while programming.
Q19. Is it possible that the ‘finally’ block will not be executed? If yes
then list the case.
Answer:
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
Suppose we use System.exit() in the above statement.
If there are fatal errors like Stack overflow, Memory access error, etc.
Q20. When can you use super keyword?
Answer:
The super keyword is used to access hidden fields and overridden methods or
attributes of the parent class.
Following are the cases when this keyword can be used:
Accessing data members of parent class when the member names of the class
and its child subclasses are same.
To call the default and parameterized constructor of the parent class inside the
child class.
Accessing the parent class methods when the child classes have overridden
them.
Q21. Can the static methods be overloaded?
Answer:
Yes! There can be two or more static methods in a class with the same name
but differing input parameters.
Q22. Why is the main method static in Java?
Answer:
The main method is always static because static members are those methods
that belong to the classes, not to an individual object. So if the main method
will not be static then for every object, It is available. And that is not
acceptable by JVM. JVM calls the main method based on the class name itself.
Not by creating the object.
Because there must be only 1 main method in the java program as the
execution starts from the main method. So for this reason the main method is
static.
Q23. Can the static methods be overridden?
Answer:
No! Declaration of static methods having the same signature can be done in
the subclass but run time polymorphism can not take place in such cases.
Overriding or dynamic polymorphism occurs during the runtime, but the static
methods are loaded and looked up at the compile time statically. Hence,
these methods cant be overridden.
Q24. Difference between static methods, static variables, and static
classes in java.
Answer:
Static Methods and Static variables are those methods and variables that
belong to the class of the java program, not to the object of the class. This
gets memory where the class is loaded. And these can directly be called with
the help of class names.
For example - We have used mathematical functions in the java program like -
max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that
we call it directly with the class name. Like - Math.max(), Math.min(), etc. So

that is a static method. And Similarly static variables we have used like
(length) for the array to get the length. So that is the static method.
Static classes - A class in the java program cannot be static except if it is the
inner class. If it is an inner static class, then it exactly works like other static
members of the class.
Q25. What is the main objective of garbage collection?
Answer:
The main objective of this process is to free up the memory space occupied by
the unnecessary and unreachable objects during the Java program execution
by deleting those unreachable objects.
This ensures that the memory resource is used efficiently, but it provides no
guarantee that there would be sufficient memory for the program execution.
Q26. What is a ClassLoader?
Answer:
Java Classloader is the program that belongs to JRE (Java Runtime
Environment). The task of ClassLoader is to load the required classes and
interfaces to the JVM when required.
Example- To get input from the console, we require the scanner class. And the
Scanner class is loaded by the ClassLoader.
Q27. What part of memory - Stack or Heap - is cleaned in garbage
collection process?
Answer:
Heap.
Q28. What are shallow copy and deep copy in java?
Answer:
Shallow copy - The shallow copy only creates a new reference and points to
the same object. Example - For Shallow copy, we can do this by -
Rectangle obj2 = obj1;
Now by doing this what will happen is the new reference is created with the
name obj2 and that will point to the same memory location.
Deep Copy - In a deep copy, we create a new object and copy the old object
value to the new object. Example -
Rectangle obj3 = new Rectangle();
Obj3.length = obj1.length;
Obj3.breadth = obj1.breadth;
Q29. Apart from the security aspect, what are the reasons behind
making strings immutable in Java?
Answer:
A String is made immutable due to the following reasons:
String Pool: Designers of Java were aware of the fact that String data type is
going to be majorly used by the programmers and developers. Thus, they
wanted optimization from the beginning. They came up with the notion of
using the String pool (a storage area in Java heap) to store the String literals.
They intended to decrease the temporary String object with the help of
sharing. An immutable class is needed to facilitate sharing. The sharing of
the mutable structures between two unknown parties is not possible. Thus,
immutable Java String helps in executing the concept of String Pool.
Multithreading: The safety of threads regarding the String objects is an
important aspect in Java. No external synchronization is required if the String
objects are immutable. Thus, a cleaner code can be written for sharing the
String objects across different threads. The complex process of concurrency
is facilitated by this method.

Collections: In the case of Hash tables and HashMaps, keys are String objects.
If the String objects are not immutable, then it can get modified during the
period when it resides in the HashMaps. Consequently, the retrieval of the
desired data is not possible. Such changing states pose a lot of risks.
Therefore, it is quite safe to make the string immutable.
Q30. What is a singleton class in Java? And How to implement a
singleton class?
Answer:
Singleton classes are those classes, whose objects are created only once. And
with only that object the class members can be accessed.
Q31. Which of the below generates a compile-time error? State the
reason.
1. int[] n1 = new int[0];
2. boolean[] n2 = new boolean[-200];
3. double[] n3 = new double[2241423798];
4. char[] ch = new char[20];
Answer:
We get a compile-time error in line 3. The error we will get in Line 3 is - integer
number too large. It is because the array requires size as an integer. And
Integer takes 4 Bytes in the memory. And the number (2241423798) is
beyond the capacity of the integer. The maximum array size we can declare is -
(2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4)
will give a compile-time error. The program will compile fine. But we get the
runtime exception in line 2. The exception is - NegativeArraySizeException.
Here what will happen is - At the time when JVM will allocate the required
memory during runtime then it will find that the size is negative. And the array
size can’t be negative. So the JVM will throw the exception.
Q32. How would you differentiate between a String, StringBuffer, and a
StringBuilder?
Answer:
Storage area: In string, the String pool serves as the storage area. For
StringBuilder and StringBuffer, heap memory is the storage area.
Mutability: A String is immutable, whereas both the StringBuilder and
StringBuffer are mutable.
Efficiency: It is quite slow to work with a String. However, StringBuilder is the
fastest in performing operations. The speed of a StringBuffer is more than a
String and less than a StringBuilder. (For example appending a character is
fastest in StringBuilder and very slow in String because a new memory is
required for the new String with appended character.)
Thread-safe: In the case of a threaded environment, StringBuilder and
StringBuffer are used whereas a String is not used. However, StringBuilder is
suitable for an environment with a single thread, and a StringBuffer is
suitable for multiple threads.
Q33. Using relevant properties highlight the differences between
interfaces and abstract classes.
Answer:
Availability of methods: Only abstract methods are available in interfaces,
whereas non-abstract methods can be present along with abstract methods
in abstract classes.

Variable types: Static and final variables can only be declared in the case of
interfaces, whereas abstract classes can also have non-static and non-final
variables.
Inheritance: Multiple inheritances are facilitated by interfaces, whereas
abstract classes do not promote multiple inheritances.
Data member accessibility: By default, the class data members of interfaces
are of the public- type. Conversely, the class members for an abstract class
can be protected or private also.
Implementation: With the help of an abstract class, the implementation of an
interface is easily possible. However, the converse is not true;
Q34. What is a Comparator in java?
Answer:
Consider the example where we have an ArrayList of employees like( EId,
Ename, Salary), etc. Now if we want to sort this list of employees based on the
names of employees. Then that is not possible to sort using the
Collections.sort() method. We need to provide something to the sort() function
depending on what values we have to perform sorting. Then in that case a
comparator is used.
Comparator is the interface in java that contains the compare method. And by
overloading the compare method, we can define that on what basis we need to
compare the values.
Q35. In Java, static as well as private method overriding is possible.
Comment on the statement.
Answer:
The statement in the context is completely False. The static methods have no
relevance with the objects, and these methods are of the class level. In the
case of a child class, a static method with a method signature exactly like that
of the parent class can exist without even throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and
overriding is certainly not possible. Private method overriding is unimaginable
because the visibility of the private method is restricted to the parent class
only. As a result, only hiding can be facilitated and not overriding.
Q36. What makes a HashSet different from a TreeSet?
Answer:
Although both HashSet and TreeSet are not synchronized and ensure that
duplicates are not present, there are certain properties that distinguish a
HashSet from a TreeSet.
Implementation: For a HashSet, the hash table is utilized for storing the
elements in an unordered manner. However, TreeSet makes use of the red-
black tree to store the elements in a sorted manner.
Complexity/ Performance: For adding, retrieving, and deleting elements, the
time amortized complexity is O(1) for a HashSet. The time complexity for
performing the same operations is a bit higher for TreeSet and is equal to
O(log n). Overall, the performance of HashSet is faster in comparison to
TreeSet.
Methods: hashCode() and equals() are the methods utilized by HashSet for
making comparisons between the objects. Conversely, compareTo() and
compare() methods are utilized by TreeSet to facilitate object comparisons.
Objects type: Heterogeneous and null objects can be stored with the help of
HashSet. In the case of a TreeSet, runtime exception occurs while inserting
heterogeneous objects or null objects.
Q37. Why is the character array preferred over string for storing
confidential information?
Answer:
In Java, a string is basically immutable i.e. it cannot be modified. After its
declaration, it continues to stay in the string pool as long as it is not removed in
the form of garbage. In other words, a string resides in the heap section of the
memory for an unregulated and unspecified time interval after string value
processing is executed.
As a result, vital information can be stolen for pursuing harmful activities by
hackers if a memory dump is illegally accessed by them. Such risks can be
eliminated by using mutable objects or structures like character arrays for
storing any variable. After the work of the character array variable is done, the
variable can be configured to blank at the same instant. Consequently, it helps
in saving heap memory and also gives no chance to the hackers to extract vital
data.
Q38. What do we get in the JDK file?
Answer:
JDK- For making java programs, we need some tools that are provided by JDK
(Java Development Kit). JDK is the package that contains various tools,
Compiler, Java Runtime Environment, etc.
JRE - To execute the java program we need an environment. (Java Runtime
Environment) JRE contains a library of Java classes + JVM. What are JAVA
Classes? It contains some predefined methods that help Java programs to
use that feature, build and execute. For example - there is a system class in
java that contains the print-stream method, and with the help of this, we can
print something on the console.
JVM - (Java Virtual Machine) JVM is a part of JRE that executes the Java
program at the end. Actually, it is part of JRE, but it is software that converts
bytecode into machine-executable code to execute on hardware.
Q39. What are the differences between HashMap and HashTable in
Java?
Answer:
HashMapHashMap HashTableHashTable
HashMap is notHashMap is not
synchronizedsynchronized
HashTable isHashTable is
synchronizedsynchronized
Allows only oneAllows only one
null key but anynull key but any
This does notThis does not
allow null in bothallow null in both
Supports order ofSupports order of
insertion byinsertion by
Order ofOrder of
insertion is notinsertion is not
Q40. What is the importance of reflection in Java?
Answer:
The term reflection is used for describing the inspection capability of a code on
other code either of itself or of its system and modify it during runtime.
Consider an example where we have an object of unknown type and we have a
method ‘fooBar()’ which we need to call on the object. The static typing
system of Java doesn't allow this method invocation unless the type of the
object is known beforehand. This can be achieved using reflection which
allows the code to scan the object and identify if it has any method called
“fooBar()” and only then call the method if needed.
Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);
methodOfFoo.invoke(fooObject, null);
Using reflection has its own cons:

Speed — Method invocations due to reflection are about three times slower
than the direct method calls.
Type safety — When a method is invoked via its reference wrongly using
reflection, invocation fails at runtime as it is not detected at compile/load
time.
Traceability — Whenever a reflective method fails, it is very difficult to find the
root cause of this failure due to a huge stack trace. One has to deep dive into
the invoke() and proxy() method logs to identify the root cause.
Hence, it is advisable to follow solutions that don't involve reflection and use
this method as a last resort.
Q41. What is the difference between the program and the process?
Answer:
A program can be defined as a line of code written in order to accomplish a
particular task. Whereas the process can be defined as the programs which
are under execution.
A program doesn't execute directly by the CPU. First, the resources are
allocated to the program and when it is ready for execution then it is a
process.
Q42. What is the difference between the ‘throw’ and ‘throws’ keyword
in java?
Answer:
The ‘throw’ keyword is used to manually throw the exception to the calling
method.
And the ‘throws’ keyword is used in the function definition to inform the
calling method that this method throws the exception. So if you are calling,
then you have to handle the exception.
Q43. Which among String or String Buffer should be preferred when
there are lot of updates required to be done in the data?
Answer:
StringBuffer is mutable and dynamic in nature whereas String is immutable.
Every updation / modification of String creates a new String thereby
overloading the string pool with unnecessary objects. Hence, in the cases of a
lot of updates, it is always preferred to use StringBuffer as it will reduce the
overhead of the creation of multiple String objects in the string pool.
Q44. What happens if the static modifier is not included in the main
method signature in Java?
Answer:
There wouldn't be any compilation error. But then the program is run, since the
JVM cant map the main method signature, the code throws
“NoSuchMethodError” error at the runtime.
Q45. Can we make the main() thread a daemon thread?
Answer:
In java multithreading, the main() threads are always non-daemon threads. And
there is no way we can change the nature of the non-daemon thread to the
daemon thread.
Q46. What happens if there are multiple main methods inside one
class in Java?
Answer:
The program can't compile as the compiler says that the method has been
already defined inside the class.
Q47. What do you understand by Object Cloning and how do you
achieve it in Java?

Answer:
It is the process of creating an exact copy of any object. In order to support
this, a java class has to implement the Cloneable interface of java.lang
package and override the clone() method provided by the Object class.
syntax :
protected Object clone() throws CloneNotSupportedException{
return (Object)super.clone();
}
In case the Cloneable interface is not implemented and just the method is
overridden, it results in CloneNotSupportedException in Java.
Q48. How does an exception propagate in the code?
Answer:
When an exception occurs, first it searches to locate the matching catch block.
In case, the matching catch block is located, then that block would be
executed. Else, the exception propagates through the method call stack and
goes into the caller method where the process of matching the catch block is
performed. This propagation happens until the matching catch block is found. If
the match is not found, then the program gets terminated in the main method.
Q49. How do exceptions affect the program if it doesn't handle them?
Answer:
Exceptions are runtime errors. Suppose we are making an android application
with java. And it all works fine but there is an exceptional case when the
application tries to get the file from storage and the file doesn’t exist (This is
the case of exception in java). And if this case is not handled properly then the
application will crash. This will be a bad experience for users. This is the type
of error that cannot be controlled by the programmer. But programmers can
take some steps to avoid this so that the application won’t crash. The proper
action can be taken at this step.
Q50. Is it mandatory for a catch block to be followed after a try block?
Answer:
No, it is not necessary for a catch block to be present after a try block. - A try
block should be followed either by a catch block or by a finally block. If the
exceptions likelihood is more, then they should be declared using the throws
clause of the method.
Q51. Can you call a constructor of a class inside the another
constructor?
Answer:
Yes, the concept can be termed as constructor chaining and can be achieved
using this().
Q52. Contiguous memory locations are usually used for storing actual
values in an array but not in ArrayList. Explain.
Answer:
In the case of ArrayList, data storing in the form of primitive data types (like int,
float, etc.) is not possible. The data members/objects present in the ArrayList
have references to the objects which are located at various sites in the
memory. Thus, storing of actual objects or non-primitive data types (like
Integer, Double, etc.) takes place in various memory locations. However, the
same does not apply to the arrays. Object or primitive type values can be
stored in arrays in contiguous memory locations, hence every element does not
require any reference to the next element.
Q53. Why does the java array index start with 0?
Answer:

It is because the 0 index array avoids the extra arithmetic operation to


calculate the memory address.
Q54. Why is the remove method faster in the linked list than in an
array?
Answer:
In the linked list, we only need to adjust the references when we want to delete
the element from either end or the front of the linked list. But in the array,
indexes are used. So to manage proper indexing, we need to adjust the values
from the array So this adjustment of value is costlier than the adjustment of
references.
Q55. What is the difference between ‘>>’ and ‘>>>’ operators in java?
Answer:
These 2 are the bitwise right shift operators. Although both operators look
similar. But there is a minimal difference between these two right shift
operators.
‘>>’ Bitwise Right Shift Operator- This operator shifts each bit to its right
position. And this maintains the signed bit.
‘>>>’ Bitwise Right Shift Operator with trailing zero- This operator also
shifts each bit to its right. But this doesn’t maintain the signed bit. This
operator makes the Most significant bit to 0.
Q56. Will the program run if we write static public void main?
Answer:
Yes, the program will successfully execute if written so. Because, in Java, there
is no specific rule for the order of specifiers.
Q57. What is the default value stored in Local Variables?
Answer:
Neither the Local Variables nor any primitives and Object references have any
default value stored in them.
Q58. What is an Association?
Answer:
An Association can be defined as a relationship that has no ownership over
another. For example, a person can be associated with multiple banks, and a
bank can be related to various people, but no one can own the other.
Q59. What is a Marker Interface?
Answer:
An empty interface in Java is referred to as a Marker interface. Serializable and
Cloneable are some famous examples of Marker Interface.
Q60. Define Wrapper Classes in Java.
Answer:
In Java, when you declare primitive datatypes, then Wrapper classes are
responsible for converting them into objects(Reference types).
Q61. How to implement a singleton class?
Answer:
singleton class given steps are to be followed:
1.
1.1.Make sure that the class has only one object
1.2.Give global access to that object
Q62. What happens when the main() isn't declared as static?
Answer:
When the main method is not declared as static, then the program may be
compiled correctly but ends up with a severe ambiguity and throws a run time
error that reads "NoSuchMethodError."

Q63. What are Brief Access Specifiers and Types of Access Specifiers?
Answer:
Access Specifiers are predefined keywords used to help JVM understand the
scope of a variable, method, and class. We have four access specifiers.
Public Access Specifier
Private Access Specifier
Protected Access Specifier
Default Access Specifier
Q64. Can a constructor return a value?
Answer:
Yes, A constructor can return a value. It replaces the class's current instance
implicitly; you cannot make a constructor return a value explicitly.
Q65. Define Late Binding.
Answer:
Binding is a process of unifying the method call with the method's code
segment. Late binding happens when the method's code segment is unknown
until it is called during the runtime.
————————————————————
DIY CODING QUESTIONS
Q1. WRITE A PROGRAM to reverse a String in Java.
Q2. Write a program to check if a vowel is present in the string.
Q3. Write a program to remove Whitespaces from String.
Q4. Write a program to remove leading and trailing whitespaces from a
string.
Q5. Write a program to Create a Deadlock Scenario Programatically.
Q6. Write a program to Revese a Linked List.
Q7. Write a program to create a Pyramid of Characters in Java.
Q8. Write a program to Check if two arrays contains same elements.
Q9. Write a program to Find second largest number in an array.
Q10. Write a program to Shuffle an Array in Java.
hint:We can use Random class to generate random index
numbers and shuffle the elements.
Q11. Write a program to find if a string is present in a text file.
Q12. Write a program to Sort HashMap by values.
Q13. Write a program to remove all occurrences of a given character
from input String.
Q14. Write a program to get distinct characters and their count in a
String.
Q15. Write a program to prove String is immutable programatically.
Q16. Write a program to showcase inheritance.
Q17. Write a Program to Show Diamond Problem with Multiple
Inheritance.
Q18. Write a Program to show try catch example.
Q19. Write a program to show NullPointerException.
Q20. Write a Java Program to reverse a string without using String
inbuilt function.
—————————————————————
TEST YOURSELF
Q1. Number of primitive data types in Java are?
1. 6
2. 7
3. 8
4. 9
Q2. What is the size of float and double in java?
1. 32 and 64
2. 32 and 32
3. 64 and 64
4. 64 and 32
Q3. Automatic type conversion is possible in which of the possible cases?
1. Byte to int
2. Int to long
3. Long to int
4. Short to int
Q4. Find the output of the following code.
int Integer = 24;
char String = ‘I’;
System.out.print(Integer);
System.out.print(String);
1. Compile error
2. Throws exception
3. I
4. 24 I
Q5. Find the output of the following program.
public class Solution{
public static void main(String[] args){
short x = 10;
x = x * 5;
System.out.print(x);
}
}
1. 50
2. 10
3. Compile error
4. Exception
Q6. Find the output of the following program.
public class Solution{
public static void main(String[] args){
byte x = 127;
x++;
x++;
System.out.print(x);
}
}
1. -127
2. 127
3. 129
4. 2
Q7. Select the valid statement.
1. char[] ch = new char(5)
2. char[] ch = new char[5]
3. char[] ch = new char()
4. char[] ch = new char[]
Q8. Find the output of the following program.

public class Solution{


public static void main(String[] args){
int[] x = {120, 200, 016};
for(int i = 0; i < x.length; i++){
System.out.print(x[i] + “ “);
}
}
}
1. 120 200 016
2. 120 200 14
3. 120 200 16
4. None
Q9. When an array is passed to a method, what does the method receive?
1. The reference of the array
2. A copy of the array
3. Length of the array
4. Copy of first element
Q10. Find the value of A[1] after execution of the following program.
int[] A = {0,2,4,1,3};
for(int i = 0; i < a.length; i++){
a[i] = a[(a[i] + 3) % a.length];
}
1. 0
2. 1
3. 2
4. 3
—————————————
ANSWERS:
1. 8
2. 32 AND 64
3. INT TO LONG
4. 24 I
5. COMPILE ERROR
6. -127
7. char[] ch = new char[5]
8. 120 200 14
9. The reference of the array
10.1
Pdf 11 - python
Q1. What is Python?
Answer:
Python is a high-level, interpreted, general-purpose programming language. Being a general-
purpose language, it ca
n be used to build almost any type of application with the right tools/libraries. Additionally,
python supports objects,
modules, threads, exception-handling, and automatic memory management which help in
modelling real-world prob
lems and building applications to solve these problems.
Q2. What are the benefits of using Python?
Answer:
* Python is a general-purpose programming language that has a simple, easy-to-learn syntax that
emphasizes readabi
lity and therefore reduces the cost of program maintenance. Moreover, the language is capable of
scripting, is compl
etely open-source, and supports third-party packages encouraging modularity and code reuse.
* Its high-level data structures, combined with dynamic typing and dynamic binding, attract a
huge community of de
velopers for Rapid Application Development and deployment.
Q3. What is a dynamically typed language?
Answer:
Typing refers to type-checking in programming languages. In a strongly-typed language, such as
Python, "1" + 2 wil
l result in a type error since these languages don't allow for "type-coercion" (implicit conversion
of data types). On t
he other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.
Type-checking can be done at two stages -
* Static - Data Types are checked before execution.
* Dynamic - Data Types are checked during execution.
Python is an interpreted language, executes each statement line by line and thus type-checking is
done on the fly, dur
ing execution. Hence, Python is a Dynamically Typed Language.
Q4. What is an Interpreted language?
Answer:
An Interpreted language executes its statements line by line. Languages such as Python,
Javascript, R, PHP, and Rub
y are prime examples of Interpreted languages. Programs written in an interpreted language runs
directly from the so
urce code, with no intermediary compilation step.
Q5. What is PEP 8 and why is it important?
Answer:
PEP stands for Python Enhancement Proposal. A PEP is an official design document providing
information to the Py
thon community, or describing a new feature for Python or its processes. PEP 8 is especially
important since it docu
ments the style guidelines for Python Code. Apparently contributing to the Python open-source
community requires
you to follow these style guidelines sincerely and strictly.
Q6. What is Scope in Python?
Answer:
A scope is a block of code where an object in Python remains relevant. Namespaces uniquely
identify all the objects
inside a program. However, these namespaces also have a scope defined for them where you
could use their objects
without any prefix.
Q7. What are the different type of scope in python?
Answer:
* A local scope refers to the local objects available in the current function.
* A global scope refers to the objects available throughout the code execution since their
inception.

* A module-level scope refers to the global objects of the current module accessible in the
program.
* An outermost scope refers to all the built-in names callable in the program. The objects in this
scope are searched l
ast to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords such as
global.
Q8. What are lists and tuples?
Answer:
Lists and Tuples are both sequence data types that can store a collection of objects in Python.
The objects stored in b
oth sequences can have different data types. Lists are represented with square brackets ['sara', 6,
0.19], while tuples a
re represented with parantheses ('ansh', 5, 0.97).
But what is the real difference between the two? The key difference between the two is that
while lists are mutable, t
uples on the other hand are immutable objects. This means that lists can be modified, appended
or sliced on the go b
ut tuples remain constant and cannot be modified in any manner.
Q9. What are the common built-in data types in Python?
Answer:
Python doesn't require data types to be defined explicitly during variable declarations type errors
are likely to occur i
f the knowledge of data types and their compatibility with each other are neglected. Python
provides type() and isinst
ance() functions to check the type of these variables.
These data types can be grouped into the following categories-
* None Type: None keyword represents the null values in Python. Boolean equality operation
can be performed us
ing these NoneType objects.
* Numeric Types: There are three distinct numeric types - integers, floating-point numbers, and
complex numbers.
Additionally, booleans are a sub-type of integers.
* Sequence Types: According to Python Docs, there are three basic Sequence Types - lists,
tuples, and range objec
ts. Sequence types have the in and not in operators defined for their traversing their elements.
These operators share t
he same priority as the comparison operations.
* Mapping Types:
A mapping object can map hashable values to random objects in Python. Mappings objects are
mutable and there is
currently only one standard mapping type, the dictionary.
* Set Types: Currently, Python has two built-in set types - set and frozenset. set type is mutable
and supports meth
ods like add() and remove(). frozenset type is immutable and can't be modified after creation.
* Modules: Module is an additional built-in type supported by the Python Interpreter. It supports
one special operat
ion, i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a
name defined in m's sy
mbol table. The module's symbol table resides in a very special attribute of the module _dict_,
but direct assignment
to this module is neither possible nor recommended.
* Callable Types: Callable types are the types to which function call can be applied. They can be
user-defined func
tions, instance methods, generator functions, and some other built-in functions, methods and
classes.
Q10. What is pass in Python?
Answer:
The pass keyword represents a null operation in Python. It is generally used for the purpose of
filling up empty block
s of code which may execute during runtime but has yet to be written. Without the pass statement
in the following co
de, we may run into some errors during code execution.
Q11. What are modules and packages in Python?
Answer:
Modules, are simply Python files with a .py extension and can have a set of functions, classes, or
variables defined a
nd implemented. They can be imported and initialized once using the import statement. If partial
functionality is nee
ded, import the requisite classes or functions using from foo import bar. Packages allow for
hierarchical structuring of the module namespace using dot notation. As, modules help avoid clas
hes between global variable names, in a similar manner, packages help avoid clashes between module
names. Crea
ting a package is easy since it makes use of the system's inherent file structure. So just stuff the modules
into a folder
and there you have it, the folder name as the package name. Importing a module or its contents from
this package re
quires the package name as prefix to the module name joined by a dot

Q12. What are global, protected and private attributes in Python?


Answer:
* Global variables are public variables that are defined in the global scope. To use the variable in
the global scope in
side a function, we use the global keyword.
* Protected attributes are attributes defined with an underscore prefixed to their identifier eg.
_sara. They can still be
accessed and modified from outside the class they are defined in but a responsible developer
should refrain from doi
ng so.
* Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh.
They cannot be acces
sed or modified from the outside directly and will result in an AttributeError if such an attempt is
made.
Q13. What is the use of self in Python?
Answer:
Self is used to represent the instance of the class. With this keyword, you can access the
attributes and methods of th
e class in python. It binds the attributes with the given arguments. self is used in different places
and often thought to
be a keyword. But unlike in C++, self is not a keyword in Python.
Q14. What is _init_?
Answer:
_init_ is a constructor method in Python and is automatically called to allocate memory when a
new object/instance i
s created. All classes have a _init_ method associated with them. It helps in distinguishing
methods and attributes of
a class from local variables.
Q15. What is break, continue and pass in Python?
Answer:
Break- The break statement terminates the loop immediately and the control flows to the
statement after the body of
the loop.
Continue- The continue statement terminates the current iteration of the statement, skips the rest
of the code in the cu
rrent iteration and the control flows to the next iteration of the loop.
Pass- the pass keyword in Python is generally used to fill up empty blocks and is similar to an
empty statement repre
sented by a semi-colon in languages such as Java, C++, Javascript, etc.
Q16. What are unit tests in Python?
Answer:
* Unit test is a unit testing framework of Python.
* Unit testing means testing different components of software separately. Can you think about
why unit testing is im
portant? Imagine a scenario, you are building software that uses three components namely A, B,
and C. Now, suppos
e your software breaks at a point time. How will you find which component was responsible for
breaking the softwar
e? Maybe it was component A that failed, which in turn failed component B, and this actually
failed the software. Th
ere can be many such combinations.
* This is why it is necessary to test each and every component properly so that we know which
component might be
highly responsible for the failure of the software.
Q17. What is docstring in Python?
Answer:
* Documentation string or docstring is a multiline string used to document a specific code
segment.
* The docstring should describe what the function or method does.

Q18. What is slicing in Python?


Answer:
* As the name suggests, ‘slicing’ is taking parts of.
* Syntax for slicing is [start : stop : step]
* start is the starting index from where to slice a list or tuple
* stop is the ending index or where to sop.
* step is the number of steps to jump.
* Default value for start is 0, stop is number of items, step is 1.
* Slicing can be done on strings, arrays, lists, and tuples.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]
Q19. Explain how can you make a Python Script executable on Unix?
Answer:
Script file must begin with #!/usr/bin/env python
Q20. What is the difference between Python Arrays and lists?
Answer:
* Arrays in python can only contain elements of same data types i.e., data type of array should be
homogeneous. It is
a thin wrapper around C language arrays and consumes far less memory than lists.
* Lists in python can contain elements of different data types i.e., data type of lists can be
heterogeneous. It has the d
isadvantage of consuming large memory.
Q21. How is memory managed in Python?
Answer:
* Memory management in Python is handled by the Python Memory Manager. The memory
allocated by the manag
er is in form of a private heap space dedicated to Python. All Python objects are stored in this
heap and being private
, it is inaccessible to the programmer. Though, python does provide some core API functions to
work upon the privat
e heap space.
* Additionally, Python has an in-built garbage collection to recycle the unused memory for the
private heap space.
Q22. What are Python namespaces? Why are they used?
Answer:
A namespace in Python ensures that object names in a program are unique and can be used
without any conflict. Pyt
hon implements these namespaces as dictionaries with 'name as key' mapped to a corresponding
'object as value'. Thi
s allows for multiple namespaces to use the same name and map it to a separate object. A few
examples of namespac
es are as follows:
* Local Namespace includes local names inside a function. the namespace is temporarily created
for a function call a
nd gets cleared when the function returns.
* Global Namespace includes names from various imported packages/ modules that are being
used in the current pro
ject. This namespace is created when the package is imported in the script and lasts until the
execution of the script.
* Built-in Namespace includes built-in functions of core Python and built-in names for various
types of exceptions.
The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope
of an object ends, t
he lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner
namespace objects from an ou
ter namespace.
Q23. What is Scope Resolution in Python?
Answer:
Sometimes objects within the same scope have the same name but function differently. In such
cases, scope resolutio
n comes into play in Python automatically.
Example:

* Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of
them - log10(), acos(
), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective
module, like math.exp() an
d cmath.exp().
* Consider the code below, an object temp has been initialized to 10 globally and then to 20 on
function call. Howev
er, the function call didn't change the value of the temp globally. Here, we can observe that
Python draws a clear line
between global and local variables, treating their namespaces as separate identities.
temp = 10 # global-scope variable
def func():
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 10
This behavior can be overridden using the global keyword inside the function, as shown in the
following example:
temp = 10 # global-scope variable
def func():
global temp
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 20
Q24. What are decorators in Python?
Answer:
Decorators in Python are essentially functions that add functionality to an existing function in
Python without changi
ng the structure of the function itself. They are represented the @decorator_name in Python and
are called in a botto
m-up fashion. The beauty of the decorators lies in the fact that besides adding functionality to the
output of the meth
od, they can even accept arguments for functions and can further modify those arguments before
passing it to the fun
ction itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is
implemented to enfor
ce encapsulation and thus, keep itself hidden from the global scope.
Q25. What are Dict and List comprehensions?
Answer:
Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and
filtered lists, dictio
naries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and
code that might be c
onsiderably more verbose (containing more lines of code).
Q26. What is lambda in Python?
Answer:
Lambda is an anonymous function in Python, that can accept any number of arguments, but can
only have a single e
xpression. It is generally used in situations requiring an anonymous function for a short time
period.
Q27. How do you copy an object in Python?
Answer:
In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a
binding between the exis
ting object and the target variable name. To create copies of an object in Python, we need to use
the copy module. M
oreover, there are two ways of creating copies for the given object using the copy module -
Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the
values in the origin
al object. If either of the values is a reference to other objects, just the reference addresses for the
same are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the
objects referenced by
the source object.
Q28. What is the difference between xrange and range in Python?
Answer:
xrange() and range() are quite similar in terms of functionality. They both generate a sequence of
integers, with the o
nly difference that range() returns a Python list, whereas, xrange() returns an xrange object.
Q29. What is pickling and unpickling?
Answer:
Pickling:
* Pickling is the name of the serialization process in Python. Any object in Python can be
serialized into a byte strea
m and dumped as a file in the memory. The process of pickling is compact but pickle objects can
be compressed furt
her. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable
across versions.
* The function used for the above process is pickle.dump().
Unpickling:
* Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the
objects stored in the fi
le and loads the object to memory.
* The function used for the above process is pickle.load().
Note: Python has another, more primitive, serialization module called marshall, which exists
primarily to support .py
c files in Python and differs significantly from the pickle.
Q30. What are generators in Python?
Answer:
Generators are functions that return an iterable collection of items, one at a time, in a set manner.
Generators, in gene
ral, are used to create iterators with a different approach. They employ the use of yield keyword
rather than return to
return a generator object.
Q31. What is PYTHONPATH in Python?
Answer:
PYTHONPATH is an environment variable which you can set to add additional directories
where Python will look f
or modules and packages. This is especially useful in maintaining Python libraries that you do
not wish to install in t
he global default location.
Q32. What is the use of help() and dir() functions?
Answer:
help() function in Python is used to display the documentation of modules, classes, functions,
keywords, etc. If no pa
rameter is passed to the help() function, then an interactive help utility is launched on the
console. dir() function tri
es to return a valid list of attributes and methods of the object it is called upon. It behaves
differently with different o
bjects, as it aims to produce the most relevant data, rather than the complete information.
* For Modules/Library objects, it returns a list of all attributes, contained in that module.
* For Class Objects, it returns a list of all valid attributes and base attributes.
* With no arguments passed, it returns a list of attributes in the current scope.
Q33. What is the difference between .py and .pyc files?
Answer:
* .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your
program. We get b
ytecode after compilation of .py file (source code). .pyc files are not created for all the files that
you run. It is only cr
eated for the files that you import.
* Before executing a python program python interpreter checks for the compiled files. If the file
is present, the virtua
l machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and
then python virtual ma
chine executes it.
* Having .pyc file saves you the compilation time.

Q34. How Python is interpreted?


Answer:
* Python as a language is not interpreted or compiled. Interpreted or compiled is the property of
the implementation.
Python is a bytecode(set of interpreter readable instructions) interpreted generally.
* Source code is a file with .py extension.
* Python compiles the source code to a set of instructions for a virtual machine. The Python
interpreter is an implem
entation of that virtual machine. This intermediate format is called “bytecode”.
* .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then
interpreted by the offici
al CPython or JIT(Just in Time compiler) compiled by PyPy.
Q35. How are arguments passed by value or by reference in python?
Answer:
* Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object
will not change the
value of the original object.
* Pass by reference: Reference to the actual object is passed. Changing the value of the new
object will change the v
alue of the original object.
Q36. What are iterators in Python?
Answer:
* An iterator is an object.
* It remembers its state i.e., where it is during iteration (see code below to see how)
* _iter_() method initializes an iterator.
* It has a _next() method which returns the next item in iteration and points to the next element.
Upon reaching the e
nd of iterable object __next_() must return StopIteration exception.
* It is also self-iterable.
* Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.
Q37. Explain how to delete a file in Python?
Answer:
Use command os.remove(file_name)
Example:
import os
os.remove("ChangedFile.csv")
print("File Removed!")
Q38. Explain split() and join() functions in Python?
Answer:
* You can use split() function to split a string based on a delimiter to a list of strings.
* You can use join() function to join a list of strings based on a delimiter to give a single string.
Q39. What does *args and **kwargs mean?
Answer:
*args
* *args is a special syntax used in the function definition to pass variable-length arguments.
* “*” means variable length and “args” is the name used by convention. You can use any other.
**kwargs
* **kwargs is a special syntax used in the function definition to pass variable-length keyworded
arguments.
* Here, also, “kwargs” is used just by convention. You can use any other name.
* Keyworded argument means a variable that has a name when passed to a function.
* It is actually a dictionary of the variable names and its value.

Q40. What are negative indexes and why are they used?
Answer:
* Negative indexes are the indexes from the end of the list or tuple or string.
* Arr[-1] means the last element of array Arr[]
Q41. Is it possible to call parent class without its instance creation?
Answer:
Yes, it is possible if the base class is instantiated by other child classes or if the base class is a
static method.
Q42. How is an empty class created in python?
Answer:
An empty class does not have any members defined in it. It is created by using the pass keyword
(the pass command
does nothing in python). We can create objects for this class outside the class.
Q43. Differentiate between new and override modifiers.
Answer:
The new modifier is used to instruct the compiler to use the new implementation and not the base
class function. The
Override modifier is useful for overriding a base class function inside the child class.
Q44. Why is finalize used?
Answer:
Finalize method is used for freeing up the unmanaged resources and clean up before the garbage
collection method i
s invoked. This helps in performing memory management tasks.
Q45. What is init method in python?
Answer:
The init method works similarly to the constructors in Java. The method is run as soon as an
object is instantiated. It
is useful for initializing any attributes or default behaviour of the object at the time of
instantiation.
Q46. How will you check if a class is a child of another class?
Answer:
This is done by using a method called issubclass() provided by python. The method tells us if
any class is a child of
another class by returning true or false accordingly.
Q47. What do you understand by reindexing in pandas?
Answer:
Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If
the values are miss
ing in the previous index, then NaN/NA is placed in the location. A new object is returned unless
a new index is pro
duced that is equivalent to the current one. The copy value is set to False. This is also used for
changing the index of
rows and columns in the dataframe.
Q48. Can you easily check if all characters in the given string is alphanumeric?
Answer:
This can be easily done by making use of the isalnum() method that returns true in case the string
has only alphanum
eric characters.
Another way is to use match() method from the re (regex) module as shown:
Q49. Define GIL.
Answer:
GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python
objects and aids in effecti
ve thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not
parallel computing).

Q50. What is main function in python? How do you invoke it?


Answer:
In the world of programming languages, the main is considered as an entry point of execution for
a program. But in
python, it is known that the interpreter serially interprets the file line-by-line. This means that
python does not provid
e main() function explicitly. But this doesn't mean that we cannot simulate the execution of main.
This can be done b
y defining user-defined main() function and by using the _name_ property of python file. This
_name_ variable is a s
pecial built-in variable that points to the name of the current module. This can be done as shown
below:
def main():
print("Hi Interviewbit!")
if _name=="main_":
main()
————————————————————————
DIY CODING QUESTION IN PYTHON
1. Write python function which takes a variable number of arguments.
2. WAP (Write a program) which takes a sequence of numbers and check if all numbers are
unique.
3. Write a program for counting the number of every character of a given text file.
4. Write a program to check and return the pairs of a given array A whose sum value is equal to a
target value N.
5. Write a Program to add two integers >0 without using the plus operator.
6. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:
ax + by = c. mx + ny = o
7. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 ‘b’s.
8. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.
9. Write a Program to combine two different dictionaries. While combining, if you find the same
keys, you can add
the values of these same keys. Output the new dictionary
10. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in
Google Drive?
11. Convert a given string to int using a single line of code.
We can convert a given string to an integer using a built-in function int(). e.g.-
a = ‘5’
print(int(a))
Variable ‘a’ is a string that is now converted to an integer, as shown below:
Output:
5
12. Write a code snippet to convert a string to a list.
Below is the code to convert string to list in Python.
str1 = "Analytics Vidhya"
print(str1.split(" "))
The split() function separates the given string by the defined delimiter i.e., space(” “) here.
Therefore, Analytics and
Vidhya break down to two strings in a list.
Output:
['Analytics', 'Vidhya']
13. How to Check a Number is Palindrome in Python.
14. How To Convert Lists To Strings In Python?
15. How to implement Merge Sort in Python?

16. How to Implement a Linked List in Python?


17. How to implement Python program to check Leap Year?
18. How to reverse a number in Python?
19. How to Find Prime Numbers in Python
20. How To Implement GCD In Python?
——————————————————————
TEST YOURSELF
Q1. Suppose list1 = [3,4,5,2,1,0], what is list1 after list1.pop(1)?
A. list1 = [3,4,5,2,1]
B. list1 = [3,4,5,2,0]
C. list1 = [3,5,2,1,0]
D. list1 = [3,4,5,2]
Q2. What is the output of the following statement "Hello World"[::-1]?
A. ”Hello World"
B. ”World Hello"
C. ”dlroW olleH"
D. ”olleH dlroW"
Q3. What is the difference between lists and tuples?
A. List is a sequence data type, while tuple is not.
B. Tuples are mutable but lists are immutable.
C. Tuple is a sequence data type, while lists is not.
D. Lists are mutable but tuples are immutable.
Q4. Let func = lambda a, b : (a ** b), what is the output of func(float(10),20) ?
A. 100000000000000000000
B. 1e+20
C. 100000000000000000000.0

D. 1.0e+20
Q5. Which statement is false for _init_?
A. _init_ is called manually on object creation.
B. _init_ is a constructor method in Python.
C. All classes have a _init_ method associated with them.
D. _init_ allocates memory for objects.
Q6. Which of the following is the function responsible for pickling?
A. pickle.save()
B. pickle.store()
C. pickle.pickle()
D. pickle.dump()
Q7. Which of the following is a protected attribute?
A. _sara_
B. __ansh
C. sara
D. ansh__
Q8. Which of the following is untrue for Python namespaces?
A. Python namespaces are implemented as a dictionary in Python.
B. Python namespaces have keys as addresses of the objects.
C. Lifecycle of a namespace depends upon the scope of the objects they are mapped to.
D. Namespaces ensure that object names in a program are unique.
Q9. Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'], what is the output of ["".join([i, j]) for i, j
in zip(list1, list2)]?
A. [’s’, 'a', 'r', 'a', 'a', 'n', 's', 'h']
B. [’s’, 'r', 'a', 's', 'a', 'a', 'n', 'h']
C. [‘sa', 'ra', 'an', 'sh']

D. [‘sa', 'sa', 'sn', 'sh', 'ra', 'ra', 'rn', 'rh', 'aa', 'aa', 'an', 'ah', 'sa', 'sa', 'sn', 'sh']
Q10. time.time() in Python returns?
A. Current time.
B. Current time in milliseconds.
C. Current time in milliseconds since midnight, January 1, 1970.
D. Current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time).
——————————————
Answers:
1. list1 = [3,5,2,1,0]
2. ”dlroW olleH"
3. Lists are mutable but tuples are immutable.
4. 1e+20
5. _init_ is called manually on object creation.
6. pickle.dump()
7. sara
8. Python namespaces have keys as addresses of the objects.
9. [‘sa', 'ra', 'an', 'sh']
10. Current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time)

Pdf 4 - C based Questions


Q1. Why is C called a mid-level programming language?
Answer:
C has characteristics of both assembly-level i.e. low-level and higher-level languages.
So
as a result, C is commonly called a middle-level language. Using C, a user can write an
operating system as well as create a menu-driven consumer billing system.
Q2. What are the features of the C language?
Answer:
1. It is Simple And Efficient.
2. C language is portable or Machine Independent.
3. C is a mid-level Programming Language.
4. It is a structured Programming Language.
5. It has a function-rich library.
6. Dynamic Memory Management.
7. C is super fast.
8. We can use pointers in C.
9. It is extensible.
Q3. What is a token?
Answer:
The individual elements of a program are called Tokens. There are following 6 types of
tokens are available in C:
• Identifiers
• Keywords
• Constants
• Operators
• Special Characters
• Strings
Q4. What is the use of printf() and scanf() functions?
Answer:
• printf() is used to print the output on the display.
• scanf() is used to read formatted data from the keyboard.
Q5. What's the value of the expression 5["abxdef"]?
Answer:
The string mentioned "abxdef" is an array, and the expression is equal to "abxdef"[5].
The answer is 'f'.

Q6. What is a built-in function in C?


Answer:
Built-function is also known as library functions that are provided by the system to make
the life of a developer easy by assisting them to do certain commonly used predefined
tasks. For example, if you need to print output or your program into the terminal, we use
printf() in C. The most commonly used built-in functions in C are scanf(), printf(), strcpy,
strlwr, strcmp, strlen, strcat, etc.
Q7. What is a Preprocessor?
Answer:
A preprocessor is a software program that processes a source file before sending it to
be
compiled. Inclusion of header files, macro expansions, conditional compilation, and line
control are all possible with the preprocessor.
Q8. In C, What is the #line used for?
Answer:
#line is used as a preprocessor to re-set the line number in the code, which takes a
parameter as line number. Here is an example for the same.
Q9. How can a string be converted to a number?
Answer:
The function takes the string as an input that needs to be converted to an integer.
Syntax: int atoi(const char *string)
Return Value:
• On successful conversion, it returns the desired integer value
• If the string starts with alpha-numeric char or only contains alpha-num char, 0 is
returned.
• In case string starts with numeric character but is followed by alpha-num char, the
string is converted to integer till the first occurrence of alphanumeric char.
Q10. How can a number be converted to a string?
Answer:
The function takes a pointer to an array of char elements that need to be converted, and
a
format string needs to be written in a buffer as a string
Syntax: int sprintf(char *str, const char *format, ...)
Q11. What is recursion in C?
Answer:
When a function in C calls a copy of itself, this is known as recursion. To put it another
way, when a function calls itself, this technique is called Recursion. Also, this function is
known as recursive function.
Q12. Why doesn’t C support function overloading?
Answer:
After you compile the C source, the symbol names need to be intact in the object code.
If
we introduce function overloading in our source, we should also provide name mangling
as a preventive measure to avoid function name clashes. Also, as C is not a strictly
typed
language many things(ex: data types) are convertible to each other in C. Therefore, the
complexity of overload resolution can introduce confusion
Q13. What is the difference between global int and static int declaration?
Answer:
The difference between this is in scope. A truly global variable has a global scope and is
visible everywhere in your program.global_temp is a global variable that is visible to
everything in your program, although to make it visible in other modules, you'd need an

extern int global_temp; ” in other source files if you have a multi-file project.
A static variable has a local scope but its variables are not allocated in the stack
segment
of the memory. It can have less than global scope, although - like global variables - it
resides in the .bss segment of your compiled binary.
Q14. What is a pointer in C?
Answer:
A pointer is a variable that stores or points to another variable's address. The value of a
variable is stored in a normal variable, whereas the address of a variable is stored in a
pointer variable.
Q15. Difference between const char* p and char const* p?
Answer:
• const char* p is a pointer to a const char.
• char const* p is a pointer to a char const.
Since const char and char const are the same, it's the same.
Q16. What is pointer to pointer in C?
Answer:
In C, a pointer can also be used to store the address of another pointer. A double
pointer
or pointer to pointer is such a pointer. The address of a variable is stored in the first
pointer, whereas the address of the first pointer is stored in the second pointer.
Syntax: int **p; // pointer to a pointer which is pointing to an integer

Q17. Why n++ executes faster than n+1 ?


Answer:
n++ being a unary operation, it just needs one variable. Whereas, n = n + 1 is a binary
operation that adds overhead to take more time (also binary operation: n += 1).
However,
in modern platforms, it depends on few things such as processor architecture, C
compiler, usage in your code, and other factors such as hardware problems. While in
the
modern compiler even if you write n = n + 1 it will get converted into n++ when it goes
into the optimized binary, and it will be equivalently efficient.
Q18. What is typecasting in C?
Answer:
Typecasting is the process to convert a variable from one datatype to another. If we
want
to store the large type value to an int type, then we will convert the data type into
another
data type explicitly.
Syntax: (data_type)expression;
Q19. What are the advantages of Macro over function?
Answer:
Macro on a high-level copy-paste, its definitions to places wherever it is called. Due to
which it saves a lot of time, as no time is spent while passing the control to a new
function and the control is always with the callee function. However, one downside is
the
size of the compiled binary is large but once compiled the program comparatively runs
faster.
Q20. What are Enumerations?
Answer:
Enumeration, also known as Enum in C, is a user-defined data type. It consists of
constant integrals or integers that have names assigned to them by the user. Because
the
integer values are named with enum in C, the whole program is simple to learn,
understand, and maintain by the same or even different programmer.
Q21. When should we use the register storage specifier?
Answer:
If a variable is used frequently, it should be declared with the register storage specifier,
and the compiler may allocate a CPU register for its storage to speed up variable
lookup.
Q22. Specify different types of decision control statements?

Answer:
All statements written in a program are executed from top to bottom one by one. Control
statements are used to execute/transfer the control from one part of the program to
another depending on the condition.
• If-else statement.
• normal if-else statement.
• Else-if statement
• nested if-else statement.
• Switch statement.
Q23. What is an r-value and l-value?
Answer:
• The term "r-value" refers to a data value stored in memory at a given address. An r-
value is an expression that cannot have a value assigned to it, hence it can only
exist on the right side of an assignment operator(=).
• The term "l-value" refers to a memory location that is used to identify an object.
The l-value can be found on either the left or right side of an assignment
operator(=). l-value is frequently used as an identifier.
Q24. What is the difference between malloc() and calloc()?
Answer:
calloc() and malloc() are memory dynamic memory allocating functions. The main
difference is that malloc() only takes one argument, which is the number of bytes, but
calloc() takes two arguments, which are the number of blocks and the size of each
block.
Q25. What is the difference between struct and union in C?
Answer:
A struct is a group of complex data structures stored in a block of memory where each
member on the block gets a separate memory location to make them accessible at once
Whereas in the union, all the member variables are stored at the same location on the
memory as a result to which while assigning a value to a member variable will change
the
value of all other members.
Q26. What is call by reference in functions?
Answer:
When we caller function makes a function call bypassing the addresses of actual
parameters being passed, then this is called call by reference. In call by reference, the
operation performed on formal parameters affects the value of actual parameters
because all the operations performed on the value stored in the address of actual
parameters.

Q27. What is pass by reference in functions?


Answer:
In Pass by reference, the callee receives the address and makes a copy of the address
of
an argument into the formal parameter. Callee function uses the address to access the
actual argument (to do some manipulation). If the callee function changes the value
addressed at the passed address it will be visible to the caller function as well.
Q28. What is a memory leak? How to avoid it?
Answer:
When we assign a variable it takes space of our RAM (either heap or RAM)dependent
on
the size of data type, however, if a programmer uses a memory available on the heap
and
forgets to a delta it, at some point all the memory available on the ram will be occupied
with no memory left this can lead to a memory leak.
To avoid memory leaks, you can trace all your memory allocations and think forward,
where you want to destroy (in a good sense) that memory and place delete there.
Q29. What is Dynamic memory allocation in C? Name the dynamic allocation
functions.
Answer:
C is a language known for its low-level control over the memory allocation of variables
in
DMA there are two major standard library malloc() and free.
The malloc() function takes a single input parameter which tells the size of the memory
requested It returns a pointer to the allocated memory. If the allocation fails, it returns
NULL. The prototype for the standard library function is like this:
void *malloc(size_t size);
The free() function takes the pointer returned by malloc() and de-allocates the memory.
No
indication of success or failure is returned. The function prototype is like this:
void free(void *pointer);
There are 4 library functions provided by C defined under <stdlib.h> header file to
facilitate dynamic memory allocation in C programming. They are:
• malloc()
• calloc()
• free()
• realloc()
Q30. What is typedef?
Answer:

typedef is a C keyword, used to define alias/synonyms for an existing type in C


language.
In most cases, we use typedef's to simplify the existing type declaration syntax. Or to
provide specific descriptive names to a type.
typedef provides an alias name to the existing complex type definition. With typedef,
you
can simply create an alias for any type. Whether it is a simple integer to complex
function
pointer or structure declaration, typedef will shorten your code.
Syntax: typedef <existing-type> <new-type-identifiers>;
Q31. Why is it usually a bad idea to use gets()? Suggest a workaround.
Answer:
The standard input library gets() reads user input till it encounters a new line character.
However, it does not check on the size of the variable being provided by the user is
under
the maximum size of the data type which makes the system vulnerable to buffer
overflow
and the input being written into memory where it isn’t supposed to.
We, therefore, use gets() to achieve the same with a restricted range of input.
Q32. What is the difference between #include "..." and #include <...>?
Answer:
In practice, the difference is in the location where the preprocessor searches for the
included file.
For #include <filename> the C preprocessor looks for the filename in the predefined list
of
system directories first and then to the directories told by the user(we can use -I option
to
add directories to the mentioned predefined list).
For #include "filename" the preprocessor searches first in the same directory as the file
containing the directive, and then follows the search path used for the #include
<filename> form. This method is normally used to include programmer-defined header
files.
Q33. What are dangling pointers? How are dangling pointers different from memory
leaks?
Answer:
The dangling pointer points to a memory that has already been freed. The storage is no
longer allocated. Trying to access it might cause a Segmentation fault. The dangling
pointer points to a memory that has already been freed. The storage is no longer
allocated. Trying to access it might cause a Segmentation fault.
A memory leak is something where the memory allocated is not freed which causes the
program to use an undefined amount of memory from the ram making it unavailable for
every other running program(or daemon) which causes the programs to crash. There
are

various tools like O profile testing which is useful to detect memory leaks on your
programs.
Q34. What is the difference between ‘g’ and “g” in C?
Answer:
In C double-quotes variables are identified as a string whereas single-quoted variables
are identified as the character. Another major difference being the string (double-
quoted)
variables end with a null terminator that makes it a 2 character array.
Q35. What is a near pointer and a far pointer in C?
Answer:
• Near Pointer: In general, the near pointer can be considered because it is used to
hold the address, which has a maximum size of just 16 bits. We can't store an
address with a size larger than 16 bits using the near pointer. All other smaller
addresses that are within the 16-bit limit, on the other hand, can be stored.
Because we can only access 64kb of data at a time, you might assume the 16 bits
are insufficient. As a result, it is regarded as one of the near-pointer's biggest
drawbacks, which is why it is no longer commonly used.
• Far Pointer: A far pointer is considered a pointer of size 32 bits. It can, however,
use the current segment to access information stored outside the computer's
memory. Although, in order to use this type of pointer, we usually need to allocate
the sector register to store the data address in the current segment.
Q36. Which structure is used to link the program and the operating system?
Answer:
The file structure is used to link the operating system and a program. The header file
"stdio.h" (standard input/output header file) defines the file. It contains information about
the file being used like its current size and its memory location. It contains a character
pointer that points to the character which is currently being opened. When you open a
file, it establishes a link between the program and the operating system about which file
is
to be accessed.
Q37. Suppose a global variable and local variable have the same name. Is it possible
to access a global variable from a block where local variables are defined?
Answer:
No. This isn’t possible in C. It’s always the most local variable that gets preference.
Q38. Which is better #define or enum?
• If we let it, the compiler can build enum values automatically. However, each of the
defined values must be given separately.
• Because macros are preprocessors, unlike enums, which are compile-time entities,
the source code is unaware of these macros. So, if we use a debugger to debug
the code, the enum is superior.
• Some compilers will give a warning if we use enum values in a switch and the
default case is missing.
• Enum always generates int-type identifiers. The macro, on the other hand, allowed
us to pick between various integral types.
• Unlike enum, the macro does not have a defined scope constraint.
Q39. Can we compile a program without a main() function?
Answer:
Yes, we can compile a program without main() function Using Macro
Q40. How do you override a defined macro?
Answer:
To override a defined macro we can use #ifdef and #undef preprocessors as follows:
• #ifdef A
• #undef A
• #endif
• #define A 10
If macro A is defined, it will be undefined using undef and then defined again using
define.
Q41. How to call a function before main()?
Answer:
To call a function before the main(), pragma startup directive should be used.
Example:
#pragma startup fun
void fun()
{
printf("In fun\n");
}
main()
{
printf("In main\n");
}
This pragma directive, on the other hand, is compiler-dependent. This is not supported
by
gcc. As a result, it will ignore the startup directive and produce no error. But the output,
in
that case, will be In main.
Q42. Differentiate between the macros and the functions.
Answer:
Q43. Differentiate Source Codes from Object Codes
Answer:
The difference between the Source Code and Object Code is that Source Code is a
collection of computer instructions written using a human-readable programming
language while Object Code is a sequence of statements in machine language, and is
the
output after the compiler or an assembler converts the Source Code.
The lastly, Object Code is the way the changes are reflected. When the Source Code is
modified, each time the Source Code needs to be compiled to reflect the changes in the
Object Code.
Q44. What are header files and what are its uses in C programming?
Answer:
In C header files must have the extension as .h, which contains function definitions,
data
type definitions, macro, etc. The header is useful to import the above definitions to the
source code using the #include directive. For example, if your source code needs to
take
input from the user do some manipulation and print the output on the terminal, it should
have stdio.h file included as #include <stdio.h>, with which we can take input using
scanf() do some manipulation and print using printf().

Q45. When is the "void" keyword used in a function?


Answer:
The keyword “void” is a data type that literally represents no data at all. The most
obvious
use of this is a function that returns nothing.The other use for the void keyword is a void
pointer. A void pointer points to the memory location where the data type is undefined at
the time of variable definition. Even you can define a function of return type void* or void
pointer meaning “at compile time we don’t know what it will return.
Q46. What is dynamic data structure?
Answer:
A dynamic data structure (DDS) refers to an organization or collection of data in
memory
that has the flexibility to grow or shrink in size, enabling a programmer to control exactly
how much memory is utilized. Dynamic data structures change in size by having unused
memory allocated or de-allocated from the heap as needed.
Dynamic data structures play a key role in programming languages like C, C++, and
Java
because they provide the programmer with the flexibility to adjust the memory
consumption of software programs.
Q47. What is the use of a static variable in C?
Answer:
• A variable which is declared as static is known as a static variable. The static
variable retains its value between multiple function calls.
• Static variables are used because the scope of the static variable is available in the
entire program. So, we can access a static variable anywhere in the program.
• The static variable is initially initialized to zero. If we update the value of a variable,
then the updated value is assigned.
• The static variable is used as a common value which is shared by all the methods.
• The static variable is initialized only once in the memory heap to reduce the
memory usage.
Q48. What is an auto keyword in C?
Answer:
in C, every local variable of a function is known as an automatic (auto) variable.
Variables
which are declared inside the function block are known as a local variable. The local
variables are also known as an auto variable. It is optional to use an auto keyword
before
the data type of a variable. If no value is stored in the local variable, then it consists of a
garbage value.
Q49. What is command line argument?
Answer:
The argument passed to the main() function while executing the program is known as
command line argument.
example:
main(int count, char *args[])
{
//code to be executed
}
Q50. What is the difference between getch() and getche()?
Answer:
The getch() function reads a single character from the keyboard. It doesn't use any
buffer,
so entered data will not be displayed on the output screen.
The getche() function reads a single character from the keyword, but data is displayed
on
the output screen. Press Alt+f5 to see the entered character.
Q51. What is the acronym for ANSI?
Answer:
The ANSI stands for " American National Standard Institute." It is an organization that
maintains the broad range of disciplines including photographic film, computer
languages, data encoding, mechanical parts, safety and more.
Q52. What is huge pointers?
Answer:
huge pointers have explicit selector. When you perform pointer arithmetic the selector
can be modified.
Q53. What are the functions to open and close the file in C language?
Answer:
The fopen() function is used to open file whereas fclose() is used to close file.
Q54. Can we access the array using a pointer in C language?
Answer:
Yes, by holding the base address of array into a pointer, we can access the array using
a
pointer.
Q55. Who is the main contributor in designing the C language after Dennis Ritchie?
Answer:
Brain Kernighan
Q56. What is the use of a semicolon (;) at the end of every program statement?

Answer:
It is majorly related to how the compiler reads( or parses) the entire code and breaks it
into a set of instructions(or statements), to which semicolon in C acts as a boundary
between two sets of instructions.
Q57. Can you tell me how to check whether a linked list is circular?
Answer:
Circular linked list is a variation of a linked list where the last node is pointing to the first
node's information part. Therefore the last node does not point to null.
Algorithm to find a circular linked list:
• Traverse the linked list
• Check if the node is pointing to the head.
• If yes then it is circular.
———————————————————
DIY Coding Questions
Q1. How can you remove duplicates in an array? Illustrate with a code.
Q2. Write a program to get the higher and lower nibble of a byte without using shift
operator?
Q3. Write a program to check if it is a palindrome number or not using a recursive
method.
Q4. Write a program to check the given number format is in binary or not.
Q5. Write a Program to find a sum of digits of a number using recursion.
Q6. Write a program to Add Two Numbers Without Using the Addition Operator and
Subtract Two Number Without Using Subtraction Operator.
Q7. Multiply an Integer Number by 2 Without Using Multiplication Operator.
Q8. Write a programCheck whether the number is EVEN or ODD, without using any
arithmetic or relational operators.
Q9. Write a program to Reverse the Linked List. Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL.
Q10. Write a program to print "hello world" without using a semicolon?
Q11. Write a program to print Fibonacci series without using recursion?

Q12. Write a program to swap two numbers without using the third variable?
Q13. Write a program to find the node at which the intersection of two singly linked
lists begins.
Q14. Write a program to Merge Two sorted Linked List.
Q15. Check for Balanced Parentheses using Stack
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the
input string is valid.
An input string is valid if:
• Open brackets must be closed by the same type of brackets.
• Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
————————————————
TEST YOURSELF
Q1. C variable cannot start with which of the following option
A. An alphabet
B. A number
C. A special symbol other than underscore
D. Both (B) and (C)
Q2. During function call, Default Parameter Passing Mechanism is called as
A. Call by Value
B. Call by reference
C. Call by address
D. Call by name
Q3. The statement printf(“%d”, 10 ? 0 ? 5 : 1 : 12); will print?

A. 10
B. 0
C. 12
D. 1
Q4. In the switch statement, each case instance value must be _______?
A. Constant
B. Variable
C. Special symbol
D. None to the above
Q5. Which is the correct syntax to declare constants in C?
A. int constant var =10;
B. int const var = 10;
C.const int var = 10;
D. Both (B) and (C)
Q6. Bitwise operators can operate upon?
A. double and chars
B. floats and doubles
C. ints and floats
D. ints and chars
Q7. The number of binary trees that can be formed using 5 nodes are
A. 30
B. 42
C. 108
D. 36
Q8. What is the correct syntax to access the value of struct variable book{ price,
page }?
A. printf("%d%d", book.price, book.page);
B. printf("%d%d", price.book, page.book);
C. printf("%d%d", price::book, page::book);
D. printf("%d%d", price->book, page->book);
Q9. Which of the following data structures is linear type?
A. String
B. Queue
C. List
D. All of the above

Q10. A binary tree with 27 nodes has _______ null branches.


A. 54
B. 27
C. 26
D. None of the above
————————————
Answer to test yourself:
1. both(B) and (C)
2. Call by value
3. 1
4. Constant
5. Both B & C
6. ints and chars
7. 42
8. printf("%d%d", book.price, book.page);
9. All of the above
10. None of the above

You might also like