Interview PDF CM
Interview PDF CM
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.
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.
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.
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
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
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
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
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?
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, &lsquo;[A-
Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}&rsquo;, &lsquo;i&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
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.
}
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:
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.
* 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
* 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.
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).
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)
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.
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().
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