Operating System Interview Question

Operating System Interview Question

A list of top frequently asked  and answers are given below.

1) What is an operating system?

The operating system is a software program that facilitates computer hardware to communicate and operate with the computer software. It is the most important part of a computer system without it computer is just like a box.

2) What is the main purpose of an operating system?

There are two main purposes of an operating system:
  • It is designed to make sure that a computer system performs well by managing its computational activities.
  • It provides an environment for the development and execution of programs.

3) What are the different operating systems?

  • Batched operating systems
  • Distributed operating systems
  • Timesharing operating systems
  • Multi-programmed operating systems
  • Real-time operating systems

4) What is a socket?

A socket is used to make connection between two applications. Endpoints of the connection are called socket.

5) What is a real-time system?

Real-time system is used in the case when rigid-time requirements have been placed on the operation of a processor. It contains a well defined and fixed time constraints.

6) What is kernel?

Kernel is the core and most important part of a computer operating system which provides basic services for all parts of the OS.

7) What is monolithic kernel?

A monolithic kernel is a kernel which includes all operating system code is in single executable image.

8) What do you mean by a process?

An executing program is known as process. There are two types of processes:
  • Operating System Processes
  • User Processes

9) What are the different states of a process?

A list of different states of process:
  • New Process
  • Running Process
  • Waiting Process
  • Ready Process
  • Terminated Process

10) What is the difference between micro kernel and macro kernel?

Micro kernel: micro kernel is the kernel which runs minimal performance affecting services for operating system. In micro kernel operating system all other operations are performed by processor.
Macro Kernel: Macro Kernel is a combination of micro and monolithic kernel.

11) What is the concept of reentrancy?

It is a very useful memory saving technique that is used for multi-programmed time sharing systems. It provides functionality that multiple users can share a single copy of program during the same period.
It has two key aspects:
  • The program code cannot modify itself.
  • The local data for each user process must be stored separately.

12) What is the difference between process and program?

A program while running or executing is known as a process.

13) What is the use of paging in operating system?

Paging is used to solve the external fragmentation problem in operating system. This technique ensures that the data you need is available as quickly as possible.

14) What is the concept of demand paging?

Demand paging specifies that if an area of memory is not currently being used, it is swapped to disk to make room for an application's need.

15) What is the advantage of a multiprocessor system?

As many as processors are increased, you will get the considerable increment in throughput. It is cost effective also because they can share resources. So, the overall reliability increases.

16) What is virtual memory?

Virtual memory is a very useful memory management technique which enables processes to execute outside of memory. This technique is especially used when an executing program cannot fit in the physical memory.

17) What is thrashing?

Thrashing is a phenomenon in virtual memory scheme when the processor spends most of its time in swapping pages, rather than executing instructions.

18) What are the four necessary and sufficient conditions behind the deadlock?

These are the 4 conditions:
1) Mutual Exclusion Condition: It specifies that the resources involved are non-sharable.
2) Hold and Wait Condition: It specifies that there must be a process that is holding a resource already allocated to it while waiting for additional resource that are currently being held by other processes.
3) No-Preemptive Condition: Resources cannot be taken away while they are being used by processes.
4) Circular Wait Condition: It is an explanation of the second condition. It specifies that the processes in the system form a circular list or a chain where each process in the chain is waiting for a resource held by next process in the chain.

19) What is a thread?

A thread is a basic unit of CPU utilization. It consists of a thread ID, program counter, register set and a stack.

20) What is FCFS?

FCFS stands for First Come, First Served. It is a type of scheduling algorithm. In this scheme, if a process requests the CPU first, it is allocated to the CPU first. Its implementation is managed by a FIFO queue.

21) What is SMP?

SMP stands for Symmetric MultiProcessing. It is the most common type of multiple processor system. In SMP, each processor runs an identical copy of the operating system, and these copies communicate with one another when required.

22) What is RAID? What are the different RAID levels?

RAID stands for Redundant Array of Independent Disks. It is used to store the same data redundantly to improve the overall performance.
Following are the different RAID levels:
RAID 0 - Stripped Disk Array without fault tolerance
RAID 1 - Mirroring and duplexing
RAID 2 - Memory-style error-correcting codes
RAID 3 - Bit-interleaved Parity
RAID 4 - Block-interleaved Parity
RAID 5 - Block-interleaved distributed Parity
RAID 6 - P+Q Redundancy

23) What is deadlock? Explain.

Deadlock is a specific situation or condition where two processes are waiting for each other to complete so that they can start. But this situation causes hang for both of them.

24) Which are the necessary conditions to achieve a deadlock?

There are 4 necessary conditions to achieve a deadlock:
  • Mutual Exclusion: At least one resource must be held in a non-sharable mode. If any other process requests this resource, then that process must wait for the resource to be released.
  • Hold and Wait: A process must be simultaneously holding at least one resource and waiting for at least one resource that is currently being held by some other process.
  • No preemption: Once a process is holding a resource ( i.e. once its request has been granted ), then that resource cannot be taken away from that process until the process voluntarily releases it.
  • Circular Wait: A set of processes { P0, P1, P2, . . ., PN } must exist such that every P[ i ] is waiting for P[ ( i + 1 ) % ( N + 1 ) ].

Note: This condition implies the hold-and-wait condition, but it is easier to deal with the conditions if the four are considered separately.


25) What is Banker's algorithm?

Banker's algorithm is used to avoid deadlock. It is the one of deadlock-avoidance method. It is named as Banker's algorithm on the banking system where bank never allocates available cash in such a manner that it can no longer satisfy the requirements of all of its customers.

26) What is the difference between logical address space and physical address space?

Logical address space specifies the address that is generated by CPU. On the other hand physical address space specifies the address that is seen by the memory unit.

27) What is fragmentation?

Fragmentation is a phenomenon of memory wastage. It reduces the capacity and performance because space is used inefficiently.

28) How many types of fragmentation occur in Operating System?

There are two types of fragmentation:
  • Internal fragmentation: It is occurred when we deal with the systems that have fixed size allocation units.
  • External fragmentation: It is occurred when we deal with systems that have variable-size allocation units.

29) What is spooling?

Spooling is a process in which data is temporarily gathered to be used and executed by a device, program or the system. It is associated with printing. When different applications send output to the printer at the same time, spooling keeps these all jobs into a disk file and queues them accordingly to the printer.

30) What is the difference between internal commands and external commands?

Internal commands are the built-in part of the operating system while external commands are the separate file programs that are stored in a separate folder or directory.

31) What is semaphore?

Semaphore is a protected variable or abstract data type that is used to lock the resource being used. The value of the semaphore indicates the status of a common resource.
There are two types of semaphore:
  • Binary semaphores
  • Counting semaphores

32) What is a binary Semaphore?

Binary semaphore takes only 0 and 1 as value and used to implement mutual exclusion and synchronize concurrent processes.

33) What is Belady's Anomaly?

Belady's Anomaly is also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns.

34) What is starvation in Operating System?

Starvation is Resource management problem. In this problem, a waiting process does not get the resources it needs for a long time because the resources are being allocated to other processes.

35) What is aging in Operating System?

Aging is a technique used to avoid the starvation in resource scheduling system.

36) What are the advantages of multithreaded programming?

A list of advantages of multithreaded programming:
  • Enhance the responsiveness to the users.
  • Resource sharing within the process.
  • Economical
  • Completely utilize the multiprocessing architecture.

37) What is the difference between logical and physical address space?

Logical address specifies the address which is generated by the CPU whereas physical address specifies to the address which is seen by the memory unit.
After fragmentation

38) What are overlays?

Overlays makes a process to be larger than the amount of memory allocated to it. It ensures that only important instructions and data at any given time are kept in memory.

39) When does trashing occur?

Thrashing specifies an instance of high paging activity. This happens when it is spending more time paging instead of executing.

Java Collections Interview Questions

1) What is the difference between ArrayList and Vector?

No. ArrayList                                              Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList is not a legacy class. Vector is a legacy class.

3) ArrayList increases its size by 50% of the array size.   Vector increases its size by doubling the array size.  

2) What is the difference between ArrayList and LinkedList?

No. ArrayList                                                   LinkedList

1) ArrayList uses a dynamic array. LinkedList uses a doubly linked list.

2) ArrayList is not efficient for manipulation because too much is required. LinkedList is efficient for manipulation.

3) ArrayList is better to store and fetch data. LinkedList is better to manipulate data.

3) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in the forward direction only whereas ListIterator traverses the elements into forward and backward direction.

No.                         Iterator                                                      ListIterator

1) The Iterator traverses the elements in the forward direction only. ListIterator traverses the elements in backward and forward directions both.

2) The Iterator can be used in List, Set, and Queue. ListIterator can be used in List only.

4) What is the difference between Iterator and Enumeration?

No.                    Iterator                                                   Enumeration

1) The Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legacy elements.

2) The Iterator is fail-fast. Enumeration is not fail-fast.

3) The Iterator is slower than Enumeration. Enumeration is faster than Iterator.

5) What is the difference between List and Set?

The List can contain duplicate elements whereas Set contains unique elements.

6) What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

7) What is the difference between Set and Map?

Set contains values only whereas Map contains key and values both.

8) What is the difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains the entry(key, value). HashSet can be iterated, but HashMap needs to convert into Set to be iterated.

9) What is the difference between HashMap and TreeMap?

HashMap maintains no order, but TreeMap maintains ascending order.

10) What is the difference between HashMap and Hashtable?

No.           HashMap              Hashtable

1) HashMap is not synchronized. Hashtable is synchronized.

2) HashMap can contain one null key and multiple null values. Hashtable cannot contain any null key or null value.

11) What is the difference between Collection and Collections?

The Collection is an interface whereas Collections is a class. The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements.

12) What is the difference between Comparable and Comparator?

No.           Comparable                           Comparator

1) Comparable provides only one sort of sequence. The Comparator provides multiple sort of sequences.

2) It provides one method named compareTo(). It provides one method named compare().

3) It is found in java.lang package. It is located in java.util package.

4) If we implement the Comparable interface, The actual class is modified. The actual class is not modified.

13) What is the advantage of Properties file?

If you change the value in the properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

14) What does the hashCode() method?

The hashCode() method returns a hash code value (an integer number).

The hashCode() method returns the same integer number if two keys (by calling equals() method) are identical.

However, it is possible that two hash code numbers can have different or the same keys.

15) Why we override equals() method?

The equals method is used to check whether two objects are the same or not. It needs to be overridden if we want to check the objects based on the property.

For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

16) How to synchronize List, Set and Map elements?

Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

public static List synchronizedList(List l){}

public static Set synchronizedSet(Set s){}

public static SortedSet synchronizedSortedSet(SortedSet s){}

public static Map synchronizedMap(Map m){}

public static SortedMap synchronizedSortedMap(SortedMap m){}

17) What is the advantage of the generic collection?

If we use the generic class, we don't need typecasting. It is typesafe and checked at compile time.

18) What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value are known as hash-collision. Two separate entries will be kept in a single hash bucket to avoid the collision.

19) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

20) What is the default size of load factor in hashing based collection?

The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

SOME OTHER QUESTION ASKED BY INTERVIEWER

How to decide between HashMap and TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. 

How to decide between HashMap and TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

What are similarities and difference between ArrayList and Vector?

ArrayList and Vector are similar classes in many ways.

Both are index based and backed up by an array internally.

Both maintains the order of insertion and we can get the elements in the order of insertion.

The iterator implementations of ArrayList and Vector both are fail-fast by design.

 ArrayList and Vector both allows null values and random access to element using index number.

These are the differences between ArrayList and Vector.

Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList.

    ArrayList is faster than Vector because it doesn’t have any overhead because of synchronization.

    ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class.

What is difference between Array and ArrayList? When will you use Array over ArrayList?

Arrays can contain primitive or Objects whereas ArrayList can contain only Objects.

Arrays are fixed size whereas ArrayList size is dynamic.

Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iterator etc.

Although ArrayList is the obvious choice when we work on list, there are few times when array are good to use.

If the size of list is fixed and mostly used to store and traverse them.

For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types.

    If you are working on fixed multi-dimensional situation, using [][] is far more easier than List<List<>>

What is difference between ArrayList and LinkedList?

ArrayList and LinkedList both implement List interface but there are some differences between them.

ArrayList is an index based data structure backed by Array, so it provides random access to it’s elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to it’s previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList.

Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle.

LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.

Which collection classes provide random access of it’s elements?

ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements. Download java collections pdf for more information.

What is EnumSet?

java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s).

Which collection classes are thread-safe?

Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment. Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the clone of the collection, so they are safe to use in multi-threaded environment.

What are concurrent Collection Classes?

Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating. By design Iterator implementation in java.util packages are fail-fast and throws ConcurrentModificationException. But Iterator implementation in java.util.concurrent packages are fail-safe and we can modify the collection while iterating. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

What is BlockingQueue?

java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.

Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

What is Queue and Stack, list their differences?

Both Queue and Stack are used to store data before processing them. java.util.Queue is an interface whose implementation classes are present in java concurrent package. Queue allows retrieval of element in First-In-First-Out (FIFO) order but it’s not always the case. There is also Deque interface that allows elements to be retrieved from both end of the queue.

Stack is similar to queue except that it allows elements to be retrieved in Last-In-First-Out (LIFO) order.

Stack is a class that extends Vector whereas Queue is an interface.

What is Collections Class?

java.util.Collections is a utility class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc.

What is Comparable and Comparator interface?

Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.

But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Comparator interface because Comparable.compareTo(Object o) method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.

Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.

What is difference between Comparable and Comparator interface?

Comparable and Comparator interfaces are used to sort collection or array of objects.

Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic.

Comparator interface is used to provide different algorithms for sorting and we can chose the comparator we want to use to sort the given collection of objects.

How can we sort a list of Objects?

If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).

Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to convert list to array.

While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?

We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as argument, this will make sure that any operation to change the collection will throw UnsupportedOperationException.

How can we create a synchronized collection from given collection?

We can use Collections.synchronizedCollection(Collection c) to get a synchronized (thread-safe) collection backed by the specified collection.

What are common algorithms implemented in Collections Framework?

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.

Some of them are sorting, searching, shuffling, min-max values.

What is Big-O notation? Give some examples?

The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure. Since Collection classes are actually data structures, we usually tend to use Big-O notation to chose the collection implementation to use based on time, memory and performance.

Example 1: ArrayList get(index i) is a constant-time operation and doesn’t depend on the number of elements in the list. So it’s performance in Big-O notation is O(1).

Example 2: A linear search on array or list performance is O(n) because we need to search through entire list of elements to find the element.

What are best practices related to Java Collections Framework?

Chosing the right type of collection based on the need, for example if size is fixed, we might want to use Array over ArrayList. If we have to iterate over the Map in order of insertion, we need to use TreeMap. If we don’t want duplicates, we should use Set.

Some collection classes allows to specify the initial capacity, so if we have an estimate of number of elements we will store, we can use it to avoid rehashing or resizing.

Write program in terms of interfaces not implementations, it allows us to change the implementation easily at later point of time.

Always use Generics for type-safety and avoid ClassCastException at runtime.

Use immutable classes provided by JDK as key in Map to avoid implementation of hashCode() and equals() for our custom class.

 Use Collections utility class as much as possible for algorithms or to get read-only, synchronized or empty collections rather than writing own implementation. It will enhance code-reuse with greater stability and low maintainability.

What is Java Priority Queue?

PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation. PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueing and dequeing operations. Check this post for java priority queue example.

Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?

Generics doesn’t support sub-typing because it will cause issues in achieving type safety. That’s why List<T> is not considered as a subtype of List<S> where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.

List<Long> listLong = new ArrayList<Long>();

listLong.add(Long.valueOf(10));

List<Number> listNumbers = listLong; // compiler error

listNumbers.add(Double.valueOf(1.23));

As you can see from above code that IF generics would have been supporting sub-typing, we could have easily add a Double to the list of Long that would have caused ClassCastException at runtime while traversing the list of Long.

Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];

We are not allowed to create generic arrays because array carry type information of it’s elements at runtime. This information is used at runtime to throw ArrayStoreException if elements type doesn’t match to the defined type. Since generics type information gets erased at compile time by Type Erasure, the array store check would have been passed where it should have failed. Let’s understand this with a simple example code.

List<Integer>[] intList = new List<Integer>[5]; // compile error

Object[] objArray = intList;

List<Double> doubleList = new ArrayList<Double>();

doubleList.add(Double.valueOf(1.23));

objArray[0] = doubleList; // this should fail but it would pass because at runtime intList and doubleList both are just List

Arrays are covariant by nature i.e S[] is a subtype of T[] whenever S is a subtype of T but generics doesn’t support covariance or sub-typing as we saw in last question. So if we would have been allowed to create generic arrays, because of type erasure we would not get array store exception even though both types are not related.

Q.we have in class with static,non-static block,constructor,main method so what is heirarchy for there ?

A.first execute static block(if parent class constructor available) then constructor called(if parent class constructor available) then non-static block executed after then main method

Q.what will be the output for Integer[] array=new Integer[100000*100000]; ?

A.OutOfMemoryError

Read these posts to learn about them in more detail.

Avoid ConcurrentModificationException

CopyOnWriteArrayList Example

HashMap vs ConcurrentHashMap

What is the difference between Array and ArrayList?

What is the difference between the length of an Array and size of ArrayList?

 How to convert ArrayList to Array and Array to ArrayList?

How to make Java ArrayList Read-Only?

How to remove duplicates from ArrayList?

How to reverse ArrayList?

How to sort ArrayList in descending order?

How to synchronize ArrayList?

When to use ArrayList and LinkedList?