This topic goes deeper into how an operating system manages processes. It covers the process concept and process states, the process control block (PCB), context switching, threads, inter-process communication, the critical-section problem and its solutions (semaphores), classic synchronisation problems, and deadlocks with their conditions, prevention, avoidance (Banker's algorithm) and detection.
Key points
A process is a program in execution. A program is passive (a file); a process is active (has a program counter, registers, stack, data).
Process states: new → ready → running → waiting (blocked) → ready … → terminated. The scheduler moves a process from ready to running; an I/O request moves it to waiting.
PCB stores everything about a process: process ID, state, program counter, CPU registers, scheduling information, memory information, open files, I/O status.
Context switch: saving the state of the running process in its PCB and loading the state of the next one. It is pure overhead.
Thread: the smallest unit of CPU execution inside a process. Threads of one process share code, data and files but have their own stack and registers. Multithreading improves responsiveness and resource sharing.
Inter-process communication (IPC): shared memory and message passing.
Race condition: the result depends on the order in which processes access shared data.
Critical section: the part of code that accesses shared data. A solution must satisfy mutual exclusion, progress and bounded waiting.
Semaphore (Dijkstra): an integer variable accessed only by atomic wait() (P) and signal() (V) operations. Binary semaphore (mutex) and counting semaphore.
Deadlock: a set of processes each waiting for a resource held by another, so none can proceed.
Four necessary conditions (Coffman): mutual exclusion, hold and wait, no preemption, circular wait. All four must hold together.
Handling deadlock: prevention (break one condition), avoidance (Banker's algorithm keeps the system in a safe state), detection and recovery (kill a process or preempt resources), or ignore it (ostrich approach).
Important terms
Process (प्रक्रिया) – program in execution.
PCB – data structure the OS keeps for each process.
Mutual exclusion – only one process in the critical section at a time.
Safe state – state in which the OS can give every process its maximum need in some order.
Starvation – a process waits indefinitely while others are served.
Formulas
Banker's algorithm: Need = Max − Allocation
A process Pᵢ can run if Needᵢ ≤ Available; after it finishes, Available = Available + Allocationᵢ
Semaphore operations:
wait(S) { while (S <= 0) ; S--; } signal(S) { S++; }
5 important questions
Q1. Differentiate between a process and a thread.
A process is an independent program in execution with its own memory space; creating and switching processes is costly. A thread is a lightweight unit inside a process that shares code, data and files with other threads of the same process; switching is cheaper.
Q2. State the four necessary conditions for deadlock.
Mutual exclusion (a resource used by one process at a time), hold and wait (a process holds some resources while waiting for others), no preemption (resources cannot be taken away forcibly), and circular wait (a closed chain of processes, each waiting for the next).
Q3. Five processes P0–P4, one resource type, Available = 3. Allocation = (1, 2, 2, 1, 0), Max = (4, 3, 7, 2, 4). Is the system safe?
Need = Max − Allocation = (3, 1, 5, 1, 4)
Available 3 → P1 (need 1) runs; Available = 3 + 2 = 5
P3 (need 1) runs; Available = 5 + 1 = 6
P0 (need 3) runs; Available = 6 + 1 = 7
P4 (need 4) runs; Available = 7; P2 (need 5) runs; Available = 9
Safe sequence: P1, P3, P0, P4, P2 → system is safe.
This prevents overflow, underflow and race conditions.
Exam tip
Banker's algorithm and process-state diagram questions are almost certain. In Banker's problems, write the Need table first and show Available after each process.
CPU scheduling decides which process in the ready queue gets the CPU next. Good scheduling keeps the CPU busy and gives quick response. This topic covers scheduling criteria, preemptive and non-preemptive scheduling, the main algorithms (FCFS, SJF, SRTF, Priority, Round Robin, multilevel queue), Gantt charts, and how to calculate waiting time and turnaround time.
Key points
Long-term scheduler (job scheduler) chooses which jobs enter memory. Short-term scheduler (CPU scheduler) chooses which ready process runs next. Medium-term scheduler swaps processes out and in.
Dispatcher gives control of the CPU to the selected process; the time it takes is dispatch latency.
Non-preemptive: once a process gets the CPU, it keeps it until it finishes or waits for I/O. Preemptive: the OS can take the CPU away (time slice over or a higher-priority process arrives).
Criteria: maximise CPU utilisation and throughput; minimise turnaround time, waiting time and response time.
FCFS (First Come First Served): simplest, non-preemptive; can cause the convoy effect (short jobs wait behind a long one).
SJF (Shortest Job First): picks the shortest burst; gives the minimum average waiting time; burst length must be predicted. Preemptive SJF is SRTF (Shortest Remaining Time First).
Priority scheduling: highest priority first; can cause starvation of low-priority processes, solved by ageing (slowly raising the priority of waiting processes).
Round Robin (RR): each process gets a fixed time quantum in turn; preemptive; good for time-sharing. Very large quantum makes it like FCFS; very small quantum causes too many context switches.
Multilevel queue: separate queues (e.g. system, interactive, batch) with their own algorithms. Multilevel feedback queue lets processes move between queues.
A Gantt chart is a bar showing which process runs in which time interval.
Important terms
Burst time – CPU time a process needs.
Arrival time – time a process enters the ready queue.
Turnaround time (TAT) – total time from arrival to completion.
Waiting time (प्रतीक्षा वेळ) – time spent waiting in the ready queue.
Time quantum – fixed CPU time slice in Round Robin.
Formulas
Turnaround Time = Completion Time − Arrival Time
Waiting Time = Turnaround Time − Burst Time
Response Time = First time on CPU − Arrival Time
Average = sum for all processes ÷ number of processes
Throughput = number of processes completed ÷ total time
5 important questions
Q1. Differentiate preemptive and non-preemptive scheduling.
In non-preemptive scheduling a running process keeps the CPU until it ends or blocks (FCFS, non-preemptive SJF). In preemptive scheduling the OS may interrupt it to give the CPU to another process (RR, SRTF). Preemptive gives better response but more context switches.
Q2. What is starvation? How is it removed?
Starvation is when a low-priority process waits indefinitely because higher-priority processes keep getting the CPU. It is removed by ageing: gradually increasing the priority of processes that wait for a long time.
Q3. Processes P1, P2, P3 arrive at time 0 with burst times 24, 3, 3 ms. Find average waiting time with FCFS and SJF.
SJF greatly reduces waiting time (convoy effect in FCFS).
Q4. Using Round Robin with quantum 4 ms for the same processes (P1 = 24, P2 = 3, P3 = 3, all arriving at 0), draw the Gantt chart and find average waiting and turnaround time.
Gantt: P1 0–4, P2 4–7, P3 7–10, then P1 runs 10–30 (alone, in slices of 4).
Completion: P1 = 30, P2 = 7, P3 = 10.
TAT: P1 30, P2 7, P3 10 → average = 47/3 = 15.67 ms.
Memory management is the OS function that allocates main memory to processes and keeps track of which parts are free or in use. This topic covers logical and physical addresses, contiguous allocation (fixed and variable partitions), fragmentation, paging, segmentation, virtual memory with demand paging, page replacement algorithms (FIFO, Optimal, LRU) and thrashing.
Key points
Logical (virtual) address is generated by the CPU; physical address is the actual location in RAM. The MMU (memory management unit) converts logical to physical addresses.
Swapping: moving a process temporarily from memory to disk and back.
Contiguous allocation: each process gets one continuous block. Fixed partitions or variable (dynamic) partitions.
Placement strategies for variable partitions: first fit (first hole big enough), best fit (smallest hole big enough), worst fit (largest hole).
Internal fragmentation: unused space inside an allocated block (fixed partitions, paging). External fragmentation: free memory is split into small scattered holes that cannot hold a process. Compaction removes external fragmentation by shifting processes together.
Paging: logical memory is divided into fixed-size pages, physical memory into frames of the same size. A page table maps pages to frames. Paging removes external fragmentation.
A TLB (translation look-aside buffer) is a small fast cache of page-table entries that speeds up address translation.
Segmentation: memory is divided into variable-size logical units (code, data, stack). Each address = (segment number, offset). It matches the programmer's view but has external fragmentation.
Virtual memory: lets a program run even if it is not fully in RAM; only needed pages are loaded (demand paging).
Page fault: the needed page is not in memory, so the OS loads it from disk.
Page replacement algorithms: FIFO (remove the oldest page), Optimal (remove the page not needed for the longest time in future; ideal but not practical), LRU (remove the page not used for the longest time in the past).
Belady's anomaly: in FIFO, more frames can sometimes cause more page faults.
Thrashing: the system spends more time swapping pages than executing, because processes do not have enough frames.
Important terms
Frame – fixed-size block of physical memory.
Page – fixed-size block of logical memory, same size as a frame.
Page fault – reference to a page not in main memory.
Fragmentation – wasted memory that cannot be used.
Formulas
Physical address = frame number × page size + offset
Logical address split: page number = address ÷ page size; offset = address mod page size
Number of pages = logical address space ÷ page size
Effective access time (with TLB) = h × (TLB time + memory time) + (1 − h) × (TLB time + 2 × memory time), h = hit ratio
Page fault rate = page faults ÷ total references
5 important questions
Q1. Differentiate internal and external fragmentation.
Internal fragmentation is wasted space inside an allocated block because the block is larger than needed (fixed partitions, paging). External fragmentation is free memory broken into small non-contiguous holes, so a large process cannot fit even though total free space is enough (variable partitions, segmentation).
Q2. What is thrashing?
Thrashing happens when processes do not have enough frames, so page faults occur continuously. The CPU spends most of its time moving pages between disk and memory, and useful work (CPU utilisation) drops sharply.
Q3. For the reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3 with 3 frames, find page faults using FIFO.
7 F [7]; 0 F [7,0]; 1 F [7,0,1]
2 F replace 7 → [2,0,1]; 0 hit
3 F replace 0 → [2,3,1]; 0 F replace 1 → [2,3,0]
4 F replace 2 → [4,3,0]; 2 F replace 3 → [4,2,0]; 3 F replace 0 → [4,2,3]
Total page faults = 9 (hits = 1)
Q4. For the same string and 3 frames, find page faults using LRU.
7 F, 0 F, 1 F → [7,0,1]
2 F replace 7 (least recently used) → [2,0,1]; 0 hit
3 F replace 1 → [2,0,3]; 0 hit
4 F replace 2 → [4,0,3]; 2 F replace 3 → [4,0,2]; 3 F replace 0 → [4,3,2]
Total page faults = 8 (hits = 2)
Q5. Explain paging with a diagram (in words).
Logical memory split into pages; physical memory into equal frames.
The file system is the part of the operating system that organises data on disk as files and directories. Disk scheduling decides the order in which pending disk requests are served so that the read/write head moves as little as possible. This topic covers file concepts and attributes, access methods, directory structures, allocation methods (contiguous, linked, indexed), free-space management, and the disk scheduling algorithms FCFS, SSTF, SCAN, C-SCAN and LOOK with a solved example.
Key points
A file is a named collection of related data stored on secondary storage.
File attributes: name, type (extension), location, size, protection (permissions), owner, time and date.
Access methods: sequential (one record after another, like a tape), direct/random (jump to any block), indexed (an index points to blocks).
Directory structures: single-level (all files in one directory), two-level (one directory per user), tree-structured (folders inside folders; absolute and relative paths), acyclic graph (shared files through links).
Contiguous allocation: each file occupies continuous blocks; fast access, but external fragmentation and hard to grow.
Linked allocation: each block points to the next; no external fragmentation, but only sequential access and space used by pointers. FAT (File Allocation Table) keeps these links in a table.
Indexed allocation: an index block holds the addresses of all blocks of the file; supports direct access; Unix inodes use this idea.
Free-space management: bit vector (1 bit per block), linked list of free blocks, grouping, counting.
Disk access time = seek time + rotational latency + transfer time. Scheduling aims to reduce seek time, measured as total head movement in cylinders.
FCFS: serve in arrival order — fair, but large head movement.
SSTF: serve the nearest request next — less movement, but can starve far requests.
SCAN (elevator): head moves to one end serving requests, then reverses. LOOK: like SCAN but turns at the last request instead of the disk end.
C-SCAN: serves in one direction only; at the end it jumps back to the start; gives more uniform waiting time. C-LOOK is the LOOK version.
Important terms
Block – fixed-size unit of disk storage.
Inode – Unix structure that stores a file's attributes and block addresses.
Seek time – time to move the head to the required cylinder.
Starvation – a request waiting indefinitely.
Mount – attaching a file system to the directory tree.
Formulas
Total head movement = Σ |next cylinder − current cylinder|
Average seek distance = total head movement ÷ number of requests
Bit-vector size (bytes) = number of blocks ÷ 8
Example used below: disk cylinders 0–199, head at 53, queue: 98, 183, 37, 122, 14, 124, 65, 67.
5 important questions
Q1. Compare contiguous, linked and indexed allocation.
Contiguous: fast sequential and direct access, but external fragmentation and the file size must be known in advance. Linked: no external fragmentation and files grow easily, but direct access is slow and a broken pointer loses data. Indexed: direct access without external fragmentation, but the index block takes extra space.
Q2. A disk has 2 GB of space in 4 KB blocks. How much memory does a bit vector need?
C-SCAN moving towards 199: 53 → 65 … 183 → 199 → 0 → 14 → 37; movement = 146 + 199 + 37 = 382 (counting the return jump; some books leave the jump out).
Q5. Explain the directory structures with merits and demerits.
Outline: single-level (simple; name clashes, no grouping) → two-level (separate user directories, no clashes between users; no sub-folders, hard to share) → tree-structured (sub-directories, absolute vs relative path, current directory; sharing still awkward) → acyclic-graph (shared files and folders through links; deletion and dangling links must be handled) → general graph (cycles possible, needs garbage collection).
Exam tip
For disk scheduling, always write the full order of service, then the movement for each step and the total. State the head's direction for SCAN/LOOK clearly.
Linux is a free, open-source, Unix-like operating system created by Linus Torvalds in 1991. Users talk to it through the shell, a command interpreter such as bash. This topic covers the Linux architecture and file system layout, common commands for files, directories, permissions, processes and text filtering, pipes and redirection, and writing shell scripts with variables, conditions and loops.
Key points
Architecture: hardware → kernel (core: process, memory, device and file management) → shell (reads and interprets commands) → utilities and applications → user.
Popular shells: sh (Bourne), bash (Bourne Again Shell, default on most systems), csh, ksh, zsh.
File system is one tree starting at root /: /bin (commands), /etc (configuration), /home (user folders), /root, /dev (devices), /tmp, /usr, /var (logs).
Everything is a file: regular files, directories, device files, links.
Linux is case-sensitive: File.txt and file.txt are different.
Permissions: read (r = 4), write (w = 2), execute (x = 1) for owner (u), group (g) and others (o). ls -l shows them, e.g. -rwxr-xr--.
The kernel is the core of Linux; it manages processes, memory, devices and files and talks directly to the hardware. The shell is a user program that reads typed commands, interprets them and asks the kernel to run them. Users never talk to the kernel directly.
Q2. What does chmod 754 report.txt do? Write the permission string.
7 = rwx for the owner, 5 = r-x for the group, 4 = r-- for others. The ls -l string becomes -rwxr-xr--.
Q3. Write a shell script to find the factorial of a number given as an argument.
#!/bin/bashn=$1fact=1; i=1while (( i <= n ))do fact=$((fact * i)) i=$((i + 1))doneecho "Factorial = $fact"
Run as ./fact.sh 5 → Factorial = 120. Inside (( )) variables can be used without the dollar sign.
Q4. Write a script to find the largest of three numbers.
a=$1b=$2c=$3if (( a > b && a > c )); then echo "$a is largest"elif (( b > c )); then echo "$b is largest"else echo "$c is largest"; fi
./big.sh 12 45 30 prints 45 is largest.
Q5. Explain redirection and pipes with examples.
ls > list.txt saves the listing in a file (overwrites); date >> list.txt adds a line at the end.
sort < names.txt reads input from a file; gcc a.c 2> err.txt saves error messages.
Pipe: cat marks.txt | sort -k2 -n -r | head -2 shows the two highest scorers. With lines "ravi 72, asha 85, neha 91, amit 58" the output is neha 91 and asha 85.
ls | wc -l counts files in a folder.
Exam tip
In shell scripts, never put spaces around = in assignments, and always leave spaces inside [ ]. Write the sample run and output below every script.
A computer network is a group of computers and devices connected to share data and resources. This topic covers network types (PAN, LAN, MAN, WAN), topologies, transmission media, network devices, the seven-layer OSI reference model with the job of each layer, and a comparison with the TCP/IP model.
Key points
Uses of networks: sharing files, printers and internet, communication (email, chat), centralised data, remote work.
Types by area: PAN (personal, a few metres, Bluetooth), LAN (a building or campus), MAN (a city), WAN (a country or the world; the Internet is the largest WAN).
Topologies: bus (single backbone cable), star (all nodes to a central hub/switch; most common in LANs), ring (closed loop), mesh (every node linked to others; very reliable), tree (hierarchy of stars), hybrid.
Transmission media: guided (twisted pair, coaxial cable, optical fibre) and unguided (radio waves, microwaves, infrared, satellite). Optical fibre gives the highest bandwidth and is immune to electromagnetic interference.
Devices: hub (sends to all ports, layer 1), switch (sends to the correct port using MAC address, layer 2), router (connects networks using IP address, layer 3), modem (converts digital ↔ analog), repeater (regenerates signal), gateway (connects different protocols), bridge (joins two LAN segments).
OSI model (by ISO) has 7 layers, from bottom to top: Physical, Data Link, Network, Transport, Session, Presentation, Application. Memory aid: "Please Do Not Throw Sausage Pizza Away".
Each layer serves the layer above it and uses the layer below it. Data is encapsulated (headers added) going down and decapsulated going up.
Transmission modes: simplex (one way, like TV broadcast), half duplex (both ways, one at a time, walkie-talkie), full duplex (both ways at once, telephone).
Switching: circuit switching (dedicated path, old telephone), packet switching (data in packets, Internet).
Important terms
Protocol (शिष्टाचार / नियमावली) – set of rules for communication.
Bandwidth – maximum data rate of a channel (bits per second).
MAC address – 48-bit hardware address of a network card.
Topology – physical or logical layout of a network.
end-to-end delivery, segmentation, flow and error control
TCP, UDP
3 Network
logical addressing, routing
IP, router
2 Data Link
framing, MAC addressing, error detection
Ethernet, switch
1 Physical
bits over the medium
cables, hub, repeater
Number of links in a full mesh of n nodes = n(n − 1)/2
5 important questions
Q1. Differentiate hub and switch.
A hub works at the physical layer and sends incoming data to all ports, causing more collisions. A switch works at the data link layer and forwards data only to the port of the destination MAC address, so it is faster and more secure.
Q2. How many cables are needed to connect 6 computers in a full mesh?
When bits travel over a network, noise can change a 0 into a 1 or a 1 into a 0. The data link layer adds extra (redundant) bits so the receiver can detect, and sometimes correct, such errors. This topic covers types of errors, parity checks (simple and two-dimensional), checksum, cyclic redundancy check (CRC) and Hamming code, with solved examples, plus a short note on flow control and ARQ.
Key points
Single-bit error: only one bit changes. Burst error: two or more bits change in a row (the burst length is from the first to the last changed bit).
Redundancy: extra bits added to the data only for checking.
Detection finds that an error happened; correction also finds which bit and fixes it.
Simple parity (VRC): add one bit so the total number of 1s is even (even parity) or odd (odd parity). Detects all single-bit errors, but misses errors in an even number of bits.
Two-dimensional parity (LRC + VRC): parity for each row and each column of a block; detects most burst errors and can correct a single-bit error.
Checksum: sender adds the data words using 1's complement arithmetic (carry wrapped round) and sends the complement of the sum. Receiver adds everything including the checksum; the result should be all 1s (complement = 0). Used in IP, TCP and UDP headers.
CRC: data is treated as a binary polynomial and divided (modulo-2, i.e. XOR, no carries) by a generator. If the generator has r + 1 bits, append r zeros, divide, and replace the zeros by the r-bit remainder. Receiver divides the whole frame; remainder 0 means no error. Used in Ethernet and Wi-Fi.
Hamming code: places parity bits at positions 1, 2, 4, 8 … ; each checks the positions whose binary number contains it. The receiver's check bits (syndrome) give the position of a single-bit error.
Flow control stops a fast sender from flooding a slow receiver: stop-and-wait, sliding window.
ARQ (Automatic Repeat reQuest) retransmits frames that arrive with errors: stop-and-wait ARQ, go-back-N, selective repeat.
Important terms
Redundant bits – extra bits used for checking.
Syndrome – the check result that shows whether and where an error is.
Modulo-2 arithmetic – addition and subtraction both done by XOR.
Generator polynomial – the divisor used in CRC, e.g. x³ + x² + 1 = 1101.
Code word – data bits plus redundant bits.
Formulas
Hamming: number of parity bits r must satisfy 2ʳ ≥ m + r + 1 (m = data bits)
CRC: append r zeros (r = generator bits − 1), divide by XOR, remainder = CRC
Method
Detects
Corrects
Simple parity
All single-bit errors
No
2-D parity
Most burst errors
Single-bit
Checksum
Most errors
No
CRC
All single, double, odd-count and short burst errors
No
Hamming
Single (and double, in extended form)
Single-bit
5 important questions
Q1. What is parity checking? What is its limitation?
One extra bit is added to make the count of 1s even (or odd). For data 1011001 (four 1s) the even-parity bit is 0, giving 10110010. If two bits flip, the count stays even, so the error is not detected — simple parity misses any even number of bit errors.
Q2. Find the checksum for the 8-bit words 10110011 and 01101010.
Sum: 10110011 + 01101010 = 1 00011101 (9 bits)
Wrap the carry: 00011101 + 1 = 00011110
Checksum = 1's complement = 11100001
Check at receiver: 00011110 + 11100001 = 11111111 → complement 0 → no error.
Q3. Find the CRC for data 100100 with generator 1101.
Generator has 4 bits, so append 3 zeros: 100100000
c4 c2 c1 = 110 = 6 → flip bit 6 back to get 0110011.
Q5. Explain error detection methods and compare them.
Outline: why errors occur (noise, interference) → single-bit vs burst → redundancy idea → parity (simple and 2-D) with example → checksum steps → CRC steps and where used → comparison table → mention that correction is done by Hamming code or by retransmission (ARQ).
Exam tip
In CRC, write every XOR step under the previous one and remember the remainder has one bit fewer than the generator. In Hamming, list which positions each parity bit covers before calculating.
TCP/IP is the set of protocols on which the Internet works. This topic covers the four layers of the TCP/IP model, IP addressing (IPv4 classes, subnet mask, private addresses, IPv6), TCP versus UDP, port numbers, important application protocols (HTTP, HTTPS, FTP, SMTP, DNS, DHCP), how DNS works, and basic Internet terms like ISP, URL and web browser.
Key points
The TCP/IP model has 4 layers: Network Access (Link), Internet, Transport, Application.
IP (Internet Protocol) gives each device a logical address and routes packets. It is connectionless and does not guarantee delivery.
IPv4 address: 32 bits, written as four decimal numbers 0–255 separated by dots (dotted decimal), e.g. 192.168.1.10. About 4.3 billion addresses (2³²).
Classful addressing: Class A (first octet 1–126), B (128–191), C (192–223), D (224–239, multicast), E (240–255, reserved). 127.x.x.x is loopback.
Subnet mask separates the network part from the host part: 255.255.255.0 (/24). CIDR notation writes the prefix length, e.g. 192.168.1.0/24.
Private ranges (not routed on the Internet): 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. NAT lets many private devices share one public IP.
IPv6: 128-bit address written in hexadecimal groups separated by colons; created because IPv4 addresses ran short.
TCP: connection-oriented, reliable (acknowledgements, retransmission), ordered, with flow and congestion control; uses a three-way handshake (SYN, SYN-ACK, ACK). Used for web, email, file transfer.
UDP: connectionless, no guarantee, low overhead, fast. Used for video calls, online games, DNS queries, live streaming.
Port numbers identify applications: HTTP 80, HTTPS 443, FTP 20/21, SSH 22, SMTP 25, DNS 53, POP3 110, IMAP 143.
DNS converts domain names (like a website name) into IP addresses; it is a distributed hierarchical system (root → top-level domain → authoritative server).
DHCP automatically gives IP addresses to devices joining a network.
URL parts: protocol (https), domain name, path, e.g. https://www.example.com/notes/page.html.
HTTP is the protocol of the World Wide Web (invented by Tim Berners-Lee, 1989–91); HTTPS adds encryption with TLS.
Important terms
IP address (आयपी पत्ता) – logical address of a device on a network.
Port – number that identifies a service on a host.
Socket – combination of IP address and port number.
ISP – Internet Service Provider, company that gives Internet access.
Packet – small unit of data sent over a network.
Formulas
Number of hosts in a subnet = 2ʰ − 2 (h = host bits; minus network and broadcast addresses)
Q1. Identify the class of these IPv4 addresses: 10.2.3.4, 172.20.5.1, 200.1.1.1.
10.2.3.4 – first octet 10 → Class A. 172.20.5.1 – 172 → Class B. 200.1.1.1 – 200 → Class C. (10.x and 172.20.x are also private addresses.)
Q2. What is DNS? Why is it needed?
DNS (Domain Name System) translates easy-to-remember domain names into numeric IP addresses that computers use. Without DNS, users would have to remember IP addresses for every website.
Q3. A network is 192.168.10.0/26. Find the subnet mask, number of usable hosts and the first and last usable address of the first subnet.
/26 → 26 network bits; mask = 255.255.255.192
Host bits = 32 − 26 = 6 → hosts = 2⁶ − 2 = 62
First subnet: 192.168.10.0 to 192.168.10.63 (block size 64)
Network address .0 and broadcast .63 are reserved
Usable range: 192.168.10.1 to 192.168.10.62
Q4. Explain the three-way handshake of TCP.
Client sends SYN (synchronise) with its initial sequence number.
Server replies with SYN-ACK: acknowledges the client's number and sends its own.
Client sends ACK to acknowledge the server.
Connection is now established; data transfer starts.
Connection is closed with FIN and ACK segments.
Q5. Explain the TCP/IP model with protocols at each layer.
Application: HTTP, HTTPS, FTP, SMTP, DNS, DHCP — user services.
Transport: TCP and UDP — end-to-end delivery, ports.
Internet: IP, ICMP (ping), ARP — addressing and routing.
Network access: Ethernet, Wi-Fi — physical transmission and framing.
Compare briefly with the 7-layer OSI model.
Exam tip
Subnetting numericals look hard but follow one rule: hosts = 2ʰ − 2. Practise /24, /25, /26 and /27 and you can solve most questions.
Every device on a TCP/IP network needs a unique IP address so that data can reach it. This topic covers the IPv4 address format, classful addressing (classes A to E), network and host parts, subnet masks, private and special addresses, subnetting and CIDR notation with solved problems, and a short introduction to IPv6.
Key points
An IPv4 address is 32 bits, written as four decimal numbers (octets) from 0 to 255 separated by dots, e.g. 192.168.10.75 (dotted decimal).
Each address has a network part (which network) and a host part (which device on it).
Classful addressing (old system), decided by the first octet:
Class A 1–126, default mask 255.0.0.0 (/8); Class B 128–191, 255.255.0.0 (/16); Class C 192–223, 255.255.255.0 (/24); Class D 224–239 multicast; Class E 240–255 reserved/experimental.
127.x.x.x is the loopback range (127.0.0.1 = this computer).
Private addresses (not routed on the Internet): 10.0.0.0/8, 172.16.0.0 to 172.31.255.255 (172.16.0.0/12), 192.168.0.0/16. NAT lets them share one public address.
In every network, the first address (host bits all 0) is the network address and the last (host bits all 1) is the broadcast address; neither can be given to a host.
A subnet mask has 1s for network (and subnet) bits and 0s for host bits. ANDing an IP with the mask gives the network address.
Subnetting borrows host bits to make smaller networks: less broadcast traffic, better security and organisation.
CIDR (Classless Inter-Domain Routing) writes the mask as a prefix length, e.g. 192.168.10.0/26, and allows any prefix, not only /8, /16, /24.
IPv6 uses 128-bit addresses written as eight groups of four hex digits, e.g. 2001:0db8:0000:0000:0000:0000:0000:0001, shortened to 2001:db8::1. It gives about 3.4 × 10³⁸ addresses and has no broadcast.
DHCP gives addresses automatically; ARP finds the MAC address for an IP address on a LAN.
Important terms
Octet – 8 bits of an IPv4 address.
Prefix length – number of 1s in the mask (/24).
Subnet – a smaller network made from a bigger one.
Default gateway – router address used to reach other networks.
NAT – translating private addresses to a public address.
First subnets: 172.16.0.0/19, 172.16.32.0/19, 172.16.64.0/19 (block size 32 in the third octet).
Exam tip
In subnetting problems, first find the block size (256 − mask octet); then networks, broadcasts and host ranges follow quickly. Always subtract 2 for network and broadcast when counting hosts.
Software engineering is the systematic, disciplined approach to developing, operating and maintaining software. The Software Development Life Cycle (SDLC) is the series of phases a software product passes through. This topic covers the need for software engineering, SDLC phases, process models (Waterfall, Prototype, Spiral, Incremental, Agile), requirement analysis and SRS, design tools like DFDs, testing levels and techniques, and maintenance.
Key points
Software crisis: projects running over budget and time, poor quality, hard to maintain. Software engineering arose to solve this (the term became popular after the NATO conference of 1968).
Waterfall model: phases are done one after another in a fixed order; simple, good when requirements are clear; changes are costly later.
Prototype model: build a quick working model to understand unclear requirements; user feedback refines it.
Spiral model (Barry Boehm): iterative loops, each with planning, risk analysis, engineering and evaluation; good for large, risky projects.
Incremental model: software is delivered in parts (increments), each adding features.
Agile (Agile Manifesto, 2001): short iterations (sprints), working software early, close customer collaboration, welcomes change. Scrum is a popular agile framework.
Feasibility study checks technical, economic (cost–benefit) and operational feasibility.
SRS (Software Requirements Specification) lists functional and non-functional requirements; it should be complete, consistent, unambiguous and verifiable.
Good design has high cohesion (each module does one job) and low coupling (modules depend little on each other).
Testing levels: unit, integration, system, acceptance (alpha at developer site, beta at user site). Techniques: black-box (based on requirements, inputs and outputs) and white-box (based on code structure and paths).
SDLC (सॉफ्टवेअर विकास जीवनचक्र) – phases of software development from idea to retirement.
SRS – document that states what the software must do.
Cohesion – how closely related the tasks inside one module are.
Coupling – degree of dependence between modules.
Verification vs validation – "are we building the product right?" vs "are we building the right product?"
Formulas
DFD symbols (Gane–Sarson / DeMarco style):
External entity – rectangle (source or sink of data)
Process – circle (bubble) or rounded rectangle
Data store – open-ended rectangle (two parallel lines)
Data flow – arrow with label
Level 0 DFD = context diagram (the whole system as one process)
Model
Best when
Drawback
Waterfall
requirements clear, small project
late changes costly
Prototype
requirements unclear
may encourage quick fixes
Spiral
large, high-risk project
complex, costly
Agile
requirements change often
needs close customer involvement
5 important questions
Q1. What is SRS? List its characteristics.
SRS (Software Requirements Specification) is a document describing what the system must do and its constraints. A good SRS is correct, complete, consistent, unambiguous, verifiable, modifiable and traceable.
Q2. Differentiate black-box and white-box testing.
Black-box testing checks the software against its requirements without looking at the code (equivalence partitioning, boundary value analysis). White-box testing uses knowledge of the internal code to test paths, branches and conditions (statement and branch coverage).
Q3. Explain the Waterfall model with its merits and demerits.
UML (Unified Modeling Language) is a standard visual language for designing and documenting object-oriented software. It was created by Grady Booch, James Rumbaugh and Ivar Jacobson and adopted by the Object Management Group (OMG) in 1997. This topic covers the need for modelling, structural and behavioural diagrams, and how to draw and read use case, class, sequence, activity and state chart diagrams for a simple system.
Key points
A model is a simplified picture of a system that helps the team understand, discuss and build it.
UML is a language for drawing, not a programming language or a process.
Behavioural (dynamic): use case, activity, state machine, and interaction diagrams (sequence, communication, timing, interaction overview).
Use case diagram: shows actors (stick figures — users or outside systems) and use cases (ovals — services the system gives) inside a system boundary. Relations: association (line), «include» (always used), «extend» (optional), generalisation.
Class diagram: box with three parts — class name, attributes, operations. Visibility: + public, − private, # protected.
Class relationships: association (plain line), aggregation (hollow diamond, "has-a", parts can exist alone), composition (filled diamond, parts die with the whole), generalisation/inheritance (hollow triangle arrow), dependency (dashed arrow). Multiplicity: 1, 0..1, * (many), 1..*.
Sequence diagram: objects across the top, vertical dashed lifelines, horizontal arrows for messages in time order (top to bottom); thin rectangles show activation.
Activity diagram: flow of activities like a flowchart: start (filled circle), action (rounded box), decision (diamond), fork/join (thick bar) for parallel work, end (circle with a dot).
State chart (state machine) diagram: states of one object and the events that cause transitions, e.g. an order goes Placed → Paid → Shipped → Delivered.
Component diagram shows software modules; deployment diagram shows hardware nodes and what runs on them.
Important terms
Actor – a role outside the system that interacts with it.
Use case – a goal the actor achieves with the system.
Lifeline – the existence of an object over time in a sequence diagram.
Multiplicity – how many objects can take part in a relationship.
Swimlane – a column in an activity diagram showing who does an action.
Formulas
Symbol
Meaning
+ / − / #
Public / private / protected member
Hollow triangle arrow
Generalisation (inheritance)
Hollow diamond
Aggregation (has-a, weak)
Filled diamond
Composition (strong ownership)
Dashed arrow
Dependency
1..*
One or more
5 important questions
Q1. Differentiate aggregation and composition.
Both are whole–part relationships. In aggregation the part can exist without the whole (a Department has Teachers; a teacher still exists if the department closes); it is drawn with a hollow diamond. In composition the part cannot exist without the whole (a House has Rooms); it is drawn with a filled diamond.
Q2. What is the difference between «include» and «extend»?
«include» means the base use case always uses the included one, e.g. "Withdraw cash" always includes "Validate PIN". «extend» means an optional behaviour added only in some conditions, e.g. "Print receipt" extends "Withdraw cash" when the user asks for it.
Q3. Draw (in words) a use case diagram for an online library system.
Actors: Student, Librarian, Payment gateway. Use cases inside the "Library System" box: Search book, Issue book, Return book, Pay fine, Add book, Login. Student → Search, Issue, Return, Pay fine; Librarian → Add book, Issue, Return; Pay fine is associated with Payment gateway. Issue book «include» Login; Pay fine «extend» Return book (only when late).
Q4. Draw (in words) a class diagram for Student, Course and Department.
Student (many) — enrolls in — Course (one or more): an association with multiplicity shown at each end
Department ◇— Course (aggregation, a department offers many courses)
UGStudent and PGStudent inherit from Student (hollow triangle).
Q5. Explain the sequence diagram with an example of an ATM withdrawal.
Outline: objects Customer, ATM, Bank Server, Account across the top with lifelines → messages in order: insertCard() → requestPIN() → enterPIN() → verifyPIN() to Bank → PIN OK → enterAmount() → checkBalance() on Account → debit() → dispense cash → printReceipt() → ejectCard(). Explain activation bars, return messages (dashed arrows) and that time runs downward.
Exam tip
Draw neat diagrams and label every relationship with its symbol and multiplicity. In theory answers, list the 14 diagrams in the two groups — it is a common short question.
HTML (HyperText Markup Language) gives a web page its structure and content, and CSS (Cascading Style Sheets) controls how that content looks. This topic covers the structure of an HTML document, common tags and attributes, lists, tables, links, images and forms, and then CSS syntax, selectors, the three ways to add CSS, the box model and basic layout.
Key points
HTML was created by Tim Berners-Lee (about 1991). The current standard is HTML5. HTML is a markup language, not a programming language.
An HTML element usually has an opening tag, content and a closing tag: <p>Hello</p>. Some are empty (no closing tag): <br>, <hr>, <img>.
Attributes give extra information inside the opening tag, as name="value", e.g. <img src="logo.png" alt="Logo">.
Basic structure: <!DOCTYPE html> → <html> → <head> (contains <title> and <meta>, <link> for CSS) → <body> (visible content).
Text tags: headings <h1> (largest) to <h6>; paragraph <p>; bold <b> or <strong>; italic <i> or <em>; line break <br>.
Lists: ordered <ol> (numbers), unordered <ul> (bullets), each item in <li>; description list <dl>, <dt>, <dd>.
Table: <table>, rows <tr>, header cells <th>, data cells <td>; attributes colspan and rowspan merge cells.
Forms collect input: <form action="..." method="post"> with <input type="text">, password, radio, checkbox, submit, plus <select>/<option> and <textarea>.
HTML5 semantic tags: <header>, <nav>, <section>, <article>, <footer>; media tags <audio> and <video>.
CSS rule = selector { property: value; }, e.g. p { color: blue; font-size: 16px; }
Three ways to add CSS: inline (style attribute), internal (<style> in the head), external (separate .css file linked with <link rel="stylesheet" href="style.css">). External CSS is best for big sites.
Cascading order: inline beats internal/external; more specific selectors win; if equal, the later rule wins.
Selectors: element (p), class (.note), id (#top), group (h1, h2), descendant (div p).
Box model: every element is a box of content → padding → border → margin.
Important terms
Tag (टॅग) – keyword in angle brackets that marks an element.
Attribute – extra setting written inside an opening tag.
Hyperlink – clickable link to another page or place.
Selector – part of a CSS rule that picks which elements to style.
Responsive design – page layout that adapts to phone and desktop screens (using media queries).
Formulas
Total width of a box (default content-box sizing):
Total width = width + left padding + right padding + left border + right border + left margin + right margin
Q1. Differentiate between container (paired) and empty tags.
A container tag has an opening and a closing tag with content in between, like <p>…</p> or <b>…</b>. An empty tag has no content and no closing tag, like <br>, <hr> and <img>.
Q2. What is the difference between a class selector and an id selector?
A class selector (written .name) can be used on many elements in a page. An id selector (written #name) should be unique — used for only one element. id has higher specificity than class.
Q3. A div has width 300px, padding 10px, border 2px and margin 15px on all sides. Find its total width.
JavaScript (JS) is the scripting language of the web. HTML gives a page its structure, CSS its look, and JavaScript its behaviour — it reacts to clicks, checks forms and changes the page without reloading. It was created by Brendan Eich at Netscape in 1995. This topic covers adding JS to a page, variables and data types, operators, control statements, functions, arrays, objects, the DOM, events and simple form validation.
Key points
JS runs inside the browser (client side); Node.js also runs it on servers.
Add JS with a <script> tag in the HTML page, or link a file: <script src="app.js"></script>.
Variables: var (function-scoped, old), let (block-scoped), const (block-scoped, cannot be reassigned).
JS is dynamically typed: the type belongs to the value, not the variable. Types: number, string, boolean, undefined, null, object, plus bigint and symbol.
== compares after type conversion (5 == "5" is true); === compares value and type (5 === "5" is false). Prefer ===.
+ with a string joins text: 5 + "5" gives "55"; but "5" * 2 gives 10.
Control statements: if…else, switch, for, while, do…while, for…of (arrays), for…in (object keys), break, continue.
Functions: function add(a, b) { return a + b; } or arrow form const add = (a, b) => a + b;.
Arrays: let a = [3, 8, 1]; with length, push(), pop(), sort(), map(), filter(), join().
Objects: let s = { name: "Asha", marks: 82 }; accessed as s.name.
DOM (Document Object Model): the page as a tree of objects. document.getElementById("id"), querySelector(), .innerHTML, .value, .style.
Events: onclick, onchange, onsubmit, onload, onmouseover, onkeyup. Handle them with attributes or element.addEventListener("click", fn).
Form validation on the client side gives instant feedback; the server must still check again.
Important terms
Scripting language – language interpreted at run time, often inside another program.
DOM – tree model of an HTML document that JS can change.
Event – an action such as a click or key press.
Event handler – function that runs when an event happens.
Hoisting – var declarations and function declarations are moved to the top of their scope.
Formulas
Expression
Result
Reason
5 + "5"
"55"
+ with a string joins
"5" * 2
10
* converts to number
5 == "5"
true
Loose equality converts type
5 === "5"
false
Strict: types differ
typeof null
"object"
Old language quirk
10 / 0
Infinity
No error in JS
Evaluation is left to right: "3" + 4 + 5 gives "345"; 3 + 4 + "5" gives "75"
5 important questions
Q1. Differentiate var, let and const.
var is function-scoped, can be redeclared and is hoisted. let is block-scoped and can be reassigned but not redeclared in the same block. const is block-scoped and must be given a value at declaration; it cannot be reassigned (but the contents of a const object or array can change).
Q2. Find the output: var x = 1; { var x = 2; } console.log(x); let y = 1; { let y = 2; } console.log(y);
var ignores the block, so the inner x = 2 replaces the outer one: prints 2. let creates a new y inside the block; the outer y stays 1: prints 1.
Q3. Write a function to find the factorial of a number and the largest element of an array.
function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); }let a = [3, 8, 1, 9, 4];console.log(fact(5)); gives 120 console.log(Math.max(...a)); gives 9 console.log(a.filter(x => x % 2 === 0)); gives [8, 4]
Q4. Write a JavaScript form validation that checks a name is not empty and a mobile number has exactly 10 digits.
function validate() { let n = document.getElementById("name").value; let m = document.getElementById("mobile").value; if (n === "") { alert("Enter name"); return false; } if (!/^[0-9]{10}$/.test(m)) { alert("Enter 10-digit mobile"); return false; } return true; }
Attach it with <form onsubmit="return validate()">; returning false stops the form from being sent.
Q5. What is the DOM? Explain how JavaScript handles events with an example.
Outline: DOM tree (document → html → head/body → elements) → selecting elements (getElementById, querySelector) → changing content and style (innerHTML, style.color) → events list → example: a button with addEventListener("click", ...) that changes a paragraph's text to "Welcome!" → advantages of addEventListener (many handlers, keeps JS separate from HTML).
Exam tip
For output questions, remember the two traps: + with strings joins text, and == converts types. Write === in your own programs.
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It is known for simple, readable syntax and is used in web development, data science, AI and automation. This topic covers Python features, variables and data types, operators, input/output, control statements, functions, and built-in data structures: list, tuple, set and dictionary, with basic file handling.
Key points
Features: easy syntax, interpreted, dynamically typed (no type declaration), object-oriented, huge standard library, free and open source, portable.
Indentation (spaces at the start of a line) marks a block of code instead of braces. A colon (:) starts a block after if, for, while, def.
Comments start with #. Variables are created on assignment: x = 10.
Data types: int, float, complex, str, bool (True/False), list, tuple, set, dict, NoneType. type(x) shows the type.
Operators: arithmetic (+ − * / // % ), comparison, logical (and, or, not), membership (in, not in), identity (is). / gives a float (7/2 = 3.5); // gives floor division (7//2 = 3); is power (2**3 = 8).
Input/output: input() always returns a string, so convert: n = int(input()). print() displays output.
Control statements: if, elif, else; while loop; for loop with range(); break, continue, pass.
Functions are defined with def; they may have default arguments and return several values (as a tuple). lambda creates small anonymous functions.
List: ordered, mutable, allows duplicates, written with [ ]. Tuple: ordered, immutable, ( ). Set: unordered, no duplicates, { }. Dictionary: key–value pairs, keys unique, {key: value}.
Strings are immutable; indexing starts at 0; negative index −1 is the last character; slicing s[start:stop].
Exception handling with try, except, finally.
Files: open("data.txt", "r") / "w" / "a"; read(), write(), close(); the with statement closes the file automatically.
Important terms
Interpreter (दुभाषी) – runs code line by line.
Dynamic typing – type of a variable is decided at run time by its value.
Mutable / immutable – can / cannot be changed after creation.
Slicing – taking a part of a sequence with [start:stop:step].
Module – a .py file of functions that can be imported (import math).
Formulas
Useful code lines:
Sum of 1 to n: total = sum(range(1, n + 1))
Reverse a string: s[::-1]
List of squares: [x * x for x in range(1, 6)] gives [1, 4, 9, 16, 25]
Factorial function:
def fact(n): f = 1 for i in range(1, n + 1): f = f * i return f print(fact(5)) # 120
Type
Ordered
Mutable
Duplicates
Example
list
yes
yes
yes
[1, 2, 2]
tuple
yes
no
yes
(1, 2)
set
no
yes
no
{1, 2}
dict
yes (3.7+)
yes
keys no
{"a": 1}
5 important questions
Q1. Differentiate list and tuple.
A list is mutable (items can be added, removed or changed) and uses square brackets [ ]. A tuple is immutable and uses round brackets ( ). Tuples are faster and can be used as dictionary keys; lists cannot.
Q3. Find the output: s = "PadhaiNotes"; print(s[0], s[-1], s[2:6], len(s))
s[0] = 'P'
s[-1] = 's' (last character)
s[2:6] = characters at index 2, 3, 4, 5 = 'dhai'
len(s) = 11
Output: P s dhai 11
Q4. Write a program to check whether a number is prime.
n = int(input("Enter number: ")) if n < 2: print("Not prime") else: for i in range(2, int(n ** 0.5) + 1): if n % i == 0: print("Not prime") break else: print("Prime")
The else of a for loop runs only if the loop did not break.
Q5. Explain dictionary operations with examples.
Create: d = {"roll": 1, "name": "Asha"}
Access: d["name"] gives 'Asha'; d.get("age", 0) gives 0 if key is missing.
Java is a high-level, class-based, object-oriented programming language developed by James Gosling and his team at Sun Microsystems and released in 1995 (it is now owned by Oracle). Its motto is "write once, run anywhere", because compiled Java code runs on any machine with a Java Virtual Machine. This topic covers Java features, JDK/JRE/JVM, program structure, data types, operators, control statements, classes and objects, constructors, inheritance, interfaces, packages and exception handling.
Key points
Features: simple, object-oriented, platform-independent, secure, robust (strong memory management, no explicit pointers), multithreaded, distributed, with automatic garbage collection.
The compiler (javac) converts source (.java) into bytecode (.class). The JVM (Java Virtual Machine) interprets/JIT-compiles bytecode on any platform. This gives platform independence.
JDK = development kit (compiler, tools) + JRE. JRE = JVM + libraries needed to run programs.
Every Java program is inside a class. Execution starts at public static void main(String[] args).
Primitive data types (8): byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2, Unicode), boolean.
Java has no pointers visible to the programmer, no multiple inheritance of classes, and no operator overloading (except + for strings).
Classes and objects: objects are created with new: Student s = new Student();
Constructors have the class name and no return type; this refers to the current object.
Inheritance uses extends: class B extends A. Java supports single, multilevel and hierarchical inheritance with classes; multiple inheritance is achieved through interfaces (implements).
Method overloading (compile-time) and method overriding (run-time polymorphism). super calls the parent's constructor or method.
Abstract class (may have some implemented methods) vs interface (a contract of methods a class must implement).
Packages group related classes (java.lang, java.util, java.io); import brings them in.
Exception handling: try, catch, finally, throw, throws. Checked exceptions (IOException) must be handled; unchecked (ArithmeticException, NullPointerException) need not be.
Important terms
Bytecode – platform-independent intermediate code produced by javac.
Garbage collection – automatic freeing of memory of unused objects.
Interface – collection of abstract methods (and constants) a class implements.
static – member that belongs to the class, not to objects.
Formulas
First Java program:
public class Hello { public static void main(String[] args) { System.out.println("Hello PadhaiNotes"); } }
Save as Hello.java → compile: javac Hello.java → run: java Hello
Inheritance and overriding:
class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } Animal a = new Dog(); a.sound(); // prints Bark (run-time polymorphism)
5 important questions
Q1. Why is Java called platform-independent?
Java source code is compiled into bytecode, not machine code. Bytecode runs on the JVM, and a JVM exists for every operating system. So the same .class file runs on Windows, Linux or Mac without change.
Q2. Differentiate JDK, JRE and JVM.
JVM runs bytecode. JRE = JVM + standard libraries; it is needed to run Java programs. JDK = JRE + development tools like the compiler (javac) and debugger; it is needed to write and compile programs.
Q3. Find the output and explain:
int a = 10, b = 4; System.out.println(a / b); System.out.println(a % b); System.out.println((double) a / b); System.out.println("Sum: " + a + b);
10 / 4 = 2 (integer division)
10 % 4 = 2
(double) 10 / 4 = 2.5
"Sum: " + 10 gives "Sum: 10", then + 4 gives "Sum: 104" (string joining, left to right)
Output lines: 2, 2, 2.5, Sum: 104
Q4. How does Java achieve multiple inheritance? Explain with an example.
Java does not allow a class to extend two classes (to avoid ambiguity, the diamond problem).
try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Done"); }
throw raises an exception; throws declares it in a method header.
Checked vs unchecked exceptions.
Exam tip
"Features of Java" and "JDK vs JRE vs JVM" are very common short questions. In programs, remember that String starts with a capital S and every statement ends with a semicolon.
Java can build windows, buttons and forms using two libraries: AWT (Abstract Window Toolkit), the older one in java.awt, and Swing, the newer and richer one in javax.swing. User actions such as clicks are handled through the delegation event model with listeners. This topic covers AWT vs Swing, containers and components, layout managers, the event model with listener interfaces and adapter classes, and a complete Swing program.
Key points
AWT components are heavyweight: each uses the operating system's own native widget, so the look changes with the OS.
Swing components are lightweight (drawn by Java itself), have a pluggable look and feel, and offer more widgets (tables, trees, tabbed panes). Swing class names usually start with J: JFrame, JButton, JLabel, JTextField.
Component: any visible item (button, label, text field, check box). Container: a component that holds others (Frame/JFrame, Panel/JPanel, Dialog).
A window needs a size and must be made visible: setSize(300, 150); setVisible(true);. In Swing, setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ends the program when the window closes.
Layout managers arrange components: FlowLayout (left to right, wraps; default for Panel/JPanel), BorderLayout (North, South, East, West, Center; default for Frame/JFrame), GridLayout (rows × columns of equal cells), CardLayout, GridBagLayout.
Delegation event model: a source (e.g. a button) generates an event object; a listener registered with the source receives it and handles it.
Steps: implement the listener interface → write its method → register with source.addXxxListener(listener).
Common pairs: ActionEvent → ActionListener.actionPerformed() (button click, Enter in text field); ItemEvent → ItemListener.itemStateChanged() (check box); MouseEvent → MouseListener (5 methods); KeyEvent → KeyListener (3 methods); WindowEvent → WindowListener (7 methods).
Adapter classes (MouseAdapter, KeyAdapter, WindowAdapter) give empty bodies for all methods, so you override only what you need.
Anonymous inner classes or lambda expressions can be used as listeners, e.g. b.addActionListener(e -> label.setText("Hi"));.
Event classes are in java.awt.event.
Important terms
Heavyweight component – depends on a native OS peer.
Lightweight component – drawn entirely in Java.
Event source – object on which the event happens.
Event listener – object that is notified and responds.
Adapter class – class with empty implementations of a listener interface.
AWT is the older toolkit; its components are heavyweight and use native OS widgets, so the look varies and the set of components is small. Swing is built on AWT but its components are lightweight, platform-independent in look, and much richer, with features like tooltips, icons and tables. Swing class names begin with J.
Q2. What is an adapter class? Why is it useful?
An adapter class implements a listener interface with empty methods. For example, WindowListener has seven methods, but to close a window we need only windowClosing(); by extending WindowAdapter we override just that one method instead of writing seven.
Q3. Explain the delegation event model.
Outline: three parts — event source, event object, event listener → the source keeps a list of registered listeners → on an action the source creates an event object and calls the listener's method → advantages: the UI code and handling code are separate, and only interested listeners are notified → example: JButton b → b.addActionListener(this) → actionPerformed() runs on click.
Q4. Write a Swing program that adds two numbers entered in text fields when a button is clicked.
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class AddDemo extends JFrame implements ActionListener { JTextField t1 = new JTextField(10), t2 = new JTextField(10), t3 = new JTextField(10); JButton b = new JButton("Add"); AddDemo() { setLayout(new FlowLayout()); add(t1); add(t2); add(b); add(t3); b.addActionListener(this); setSize(300, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e) { int s = Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText()); t3.setText(String.valueOf(s)); } public static void main(String[] args) { new AddDemo(); } }
Entering 12 and 30 and clicking Add shows 42 in the third box.
Q5. Explain any three layout managers with examples.
FlowLayout: places components in a row, left to right (centered by default), and wraps to the next line — setLayout(new FlowLayout());. BorderLayout: five regions, add(b, BorderLayout.NORTH); — the centre takes the extra space. GridLayout: equal-sized cells, new GridLayout(4, 4) for a calculator keypad. Mention the default layouts of Frame and Panel.
Exam tip
In GUI programs, examiners check four things: the imports, implementing the listener, registering it with addActionListener, and setVisible(true). Never skip any of them.
A finite automaton is a simple mathematical machine with a fixed number of states that reads an input string one symbol at a time and either accepts or rejects it. Finite automata recognise exactly the regular languages, which can also be written as regular expressions. This topic covers alphabets, strings and languages, DFA and NFA, converting an NFA to a DFA, regular expressions, and where these ideas are used (lexical analysis, pattern matching).
Key points
Alphabet (Σ): finite set of symbols, e.g. Σ = {0, 1}. String: finite sequence of symbols; ε is the empty string. Language: a set of strings over Σ.
Σ∗ = all strings over Σ including ε; Σ⁺ = all non-empty strings.
A DFA (Deterministic Finite Automaton) is a 5-tuple M = (Q, Σ, δ, q₀, F): states, alphabet, transition function δ: Q × Σ → Q, start state, set of final states.
In a DFA, every state has exactly one move for every symbol. The string is accepted if the machine ends in a final state.
An NFA (Non-deterministic FA) can have zero, one or many moves for a symbol (δ: Q × Σ → set of states), and an ε-NFA can also move without reading input.
Every NFA has an equivalent DFA (same language), found by subset construction; the DFA may have up to 2ⁿ states.
Drawing: states as circles, start state with an arrow, final states as double circles, arrows labelled with symbols.
Regular expression (RE) operators: union (+ or |), concatenation, Kleene star (∗ = zero or more). Precedence: star, then concatenation, then union.
Every RE has an equivalent FA and every FA has an equivalent RE (Kleene's theorem).
Regular languages are closed under union, concatenation, star, complement and intersection.
Finite automata have no memory beyond the current state, so they cannot recognise languages like { aⁿbⁿ } (needs counting) — that needs a pushdown automaton.
Uses: lexical analyser of a compiler (tokens), text search (grep), input validation, vending machines, traffic lights.
Important terms
State – a condition the machine can be in.
Transition – move from one state to another on a symbol.
Dead (trap) state – non-final state with no way out.
Kleene star – zero or more repetitions.
Regular language – language accepted by some finite automaton.
Formulas
DFA: M = (Q, Σ, δ, q₀, F), δ: Q × Σ → Q
NFA: δ: Q × Σ → 2^Q (a set of states)
Maximum DFA states from an n-state NFA = 2ⁿ
RE
Language
(0 + 1)∗01
Binary strings ending in 01
a(a + b)∗b
Strings that start with a and end with b
((a + b)(a + b))∗
Strings of even length
0∗10∗
Strings with exactly one 1
(0 + 1)∗00(0 + 1)∗
Strings containing 00
5 important questions
Q1. Differentiate DFA and NFA.
In a DFA each state has exactly one transition for each input symbol and no ε-moves; it is easy to run. In an NFA a state may have several or no transitions for a symbol and may have ε-moves; it is easier to design. Both accept the same class of languages (regular languages).
Q2. Write regular expressions for: (a) strings over {a, b} that start with a and end with b; (b) strings over {0, 1} with exactly one 1.
(a) a(a + b)∗b — first symbol a, anything in the middle, last symbol b. (b) 0∗10∗ — any number of 0s, one 1, any number of 0s.
Q3. Design a DFA over {0, 1} that accepts strings ending with 01, and trace 1101 and 0110.
State
On 0
On 1
→ q0
q1
q0
q1
q1
q2
q2 (final)
q1
q0
q0 = no useful suffix, q1 = last symbol was 0, q2 = last two were 01
1101: q0 →1 q0 →1 q0 →0 q1 →1 q2 → ends in final state → accepted
0110: q0 →0 q1 →1 q2 →1 q0 →0 q1 → not final → rejected
Q4. Convert the NFA for strings ending in 01 into a DFA. NFA: A (start) on 0 → {A, B}, on 1 → {A}; B on 1 → {C}; C final.
DFA state
On 0
On 1
→ {A}
{A, B}
{A}
{A, B}
{A, B}
{A, C}
{A, C} (final)
{A, B}
{A}
Only 3 of the 8 possible subsets are reachable. {A, C} is final because it contains C.
Renaming {A} = q0, {A, B} = q1, {A, C} = q2 gives exactly the DFA of Q3.
Q5. Explain the formal definition of a finite automaton and its applications.
Outline: define the 5-tuple with the meaning of each part → transition diagram and transition table → extended transition δ̂ for strings → acceptance condition → example DFA for even number of 0s (two states, flip on 0, stay on 1) → applications: lexical analysis, string search, protocol checking, digital circuit design → limitation: no memory, cannot count (aⁿbⁿ).
Exam tip
Always give both the transition diagram (in words or drawn) and the transition table, mark the start and final states, and trace at least one accepted and one rejected string.
A compiler translates a program written in a high-level language into an equivalent program in machine or assembly language, and reports errors. It works in phases, grouped into an analysis (front end) part and a synthesis (back end) part. This topic covers the language-processing system, the six phases of a compiler with the symbol table and error handler, a worked trace of one statement through all phases, and passes, cousins of the compiler and compiler-construction tools.
Analysis (front end): lexical, syntax and semantic analysis; it depends on the source language and builds an intermediate form.
Synthesis (back end): intermediate code generation, code optimisation, code generation; it depends on the target machine.
1. Lexical analysis (scanner): reads characters and groups them into tokens (keywords, identifiers, operators, constants, punctuation); removes spaces and comments. Patterns are given by regular expressions and recognised by finite automata. Tool: LEX/Flex.
2. Syntax analysis (parser): checks the token sequence against the grammar (context-free grammar) and builds a parse tree / syntax tree. Top-down (LL, recursive descent) or bottom-up (LR, SLR, LALR) parsers. Tool: YACC/Bison.
3. Semantic analysis: checks meaning — type checking, declared-before-use, matching function arguments; inserts type conversions (e.g. int to float).
4. Intermediate code generation: produces machine-independent code such as three-address code (at most one operator on the right of each instruction).
5. Code optimisation: improves the intermediate code to run faster or use less memory without changing results — constant folding, common sub-expression elimination, dead-code elimination, loop optimisation.
6. Code generation: chooses registers and machine instructions to produce target code.
Symbol table: data structure holding each identifier's name, type, scope and location; used by all phases.
Error handler: detects, reports and recovers from errors in every phase (lexical: illegal character; syntax: missing semicolon; semantic: type mismatch).
A pass is one reading of the whole program; a compiler can be single-pass or multi-pass.
Cousins of the compiler: preprocessor, assembler, linker, loader, interpreter.
Important terms
Token – a meaningful unit such as id, =, +, num.
Lexeme – the actual characters matched for a token, e.g. rate.
Pattern – the rule describing a token's lexemes.
Parse tree – tree showing how the grammar derives the statement.
Three-address code – instructions like t1 = b * c with at most three addresses.
Formulas
Worked trace for the statement position = initial + rate * 60 (all variables float):
Phase
Output
Lexical
id1 = id2 + id3 × 60 (id1 = position, id2 = initial, id3 = rate in the symbol table)
Syntax
Tree: = at root; left id1; right + with children id2 and (× with children id3, 60)
Semantic
60 is an int, so it is converted: id3 × inttofloat(60)
Intermediate
t1 = inttofloat(60); t2 = id3 × t1; t3 = id2 + t2; id1 = t3
Q1. Differentiate a token, a lexeme and a pattern.
A token is a category of input unit such as identifier or number. A lexeme is the actual string in the program that belongs to that token, e.g. count is a lexeme of token id. A pattern is the rule that describes all lexemes of a token, e.g. "a letter followed by letters or digits" for identifiers.
Q2. How many tokens are there in if (x >= 10) y = y + 1;?
Tokens: if, (, x, >=, 10, ), y, =, y, +, 1, ; → 12 tokens. Note that >= is one token, not two.
Q3. Explain the phases of a compiler with a neat diagram (in words).
Outline: draw source program → lexical analyser → syntax analyser → semantic analyser → intermediate code generator → code optimiser → code generator → target program, with the symbol table manager and error handler connected to every phase → explain each phase in 2–3 lines → group into front end and back end.
Q4. Write the three-address code for a = (b + c) * (b + c) - d and optimise it.
t1 = b + c
t2 = b + c
t3 = t1 × t2
t4 = t3 − d
a = t4
Optimised (common sub-expression elimination): t1 = b + c; t2 = t1 × t1; a = t2 − d. Five instructions become three.
Q5. What is code optimisation? Explain any four techniques.
Optimisation makes code faster or smaller without changing its output. Constant folding: x = 3 * 4 becomes x = 12 at compile time. Common sub-expression elimination: compute b + c once and reuse it. Dead-code elimination: remove code that can never run, e.g. statements after return. Loop-invariant code motion: move a calculation that does not change inside a loop to before the loop. Also strength reduction: replace i × 2 with i + i.
Exam tip
The trace of position = initial + rate * 60 through all six phases is the most-asked compiler question — practise writing it neatly as a table.
Cyber security is the practice of protecting computers, networks, programs and data from attack, damage or unauthorised access. This topic covers the CIA triad, types of cyber threats and malware, common attacks (phishing, DoS, man-in-the-middle, SQL injection), basics of cryptography, firewalls and antivirus, safe practices, and an introduction to cyber law in India (the IT Act, 2000).
Key points
CIA triad: Confidentiality (only authorised people can see data), Integrity (data is not changed wrongly), Availability (data and services are available when needed).
Malware (malicious software) types: virus (attaches to a file and spreads when the file runs), worm (spreads by itself over networks), Trojan horse (looks useful but does harm), ransomware (encrypts files and demands payment), spyware and keyloggers (secretly record activity), adware.
Phishing: fake emails, SMS or websites that trick people into giving passwords, OTPs or bank details. Variants: vishing (voice call), smishing (SMS).
Denial of Service (DoS): flooding a server with requests so real users cannot use it; DDoS uses many infected computers (a botnet).
Man-in-the-middle: attacker secretly intercepts communication between two parties (common on unsafe public Wi-Fi).
SQL injection: attacker types SQL code into an input box to read or change the database; prevented by input validation and parameterised queries.
Social engineering: manipulating people rather than machines (pretending to be a bank officer).
Cryptography: converting plaintext into ciphertext. Symmetric encryption uses one shared key (AES, DES). Asymmetric uses a public key and a private key (RSA). Hashing (SHA-256) gives a fixed-size fingerprint used to check integrity and store passwords.
Digital signature uses the sender's private key to prove who sent a message and that it was not changed.
Firewall: hardware or software that filters network traffic using rules. Antivirus detects and removes malware. IDS (intrusion detection system) watches for suspicious activity.
Authentication methods: something you know (password), something you have (OTP, phone), something you are (fingerprint). Using two of these is two-factor authentication (2FA).
Cyber law in India: the Information Technology Act, 2000 gives legal recognition to electronic records and digital signatures and defines cyber offences; it was amended in 2008. Section 66 deals with computer-related offences.
Complaints can be filed on the national cyber crime reporting portal; the national cyber crime helpline number is 1930.
Important terms
Cyber crime (सायबर गुन्हा) – crime using a computer or network.
Encryption – converting readable data into coded form.
Firewall – barrier that controls incoming and outgoing network traffic.
Vulnerability – weakness that an attacker can exploit.
Patch – software update that fixes a security weakness.
Formulas
Simple cipher example (Caesar cipher, shift 3):
Each letter moves 3 places forward: A → D, B → E, … X → A, Y → B, Z → C
Plaintext HELLO → ciphertext KHOOR
Decryption: move each letter 3 places back
Strong password rules: at least 8–12 characters, mix of upper case, lower case, digits and symbols; no names or birth dates; different passwords for different accounts.
Symmetric
Asymmetric
one shared secret key
public + private key pair
fast
slower
key sharing is a problem
public key can be shared openly
AES, DES
RSA, ECC
5 important questions
Q1. What is the CIA triad?
It is the basic model of information security. Confidentiality keeps data secret from unauthorised users; Integrity ensures data is accurate and not altered wrongly; Availability ensures systems and data are accessible to authorised users when needed.
Q2. Differentiate a virus and a worm.
A virus attaches itself to a host file or program and spreads only when that file is run or shared. A worm is a standalone program that copies itself across networks without needing a host file or user action, so it spreads faster.
Q3. Encrypt the word "EXAM" with a Caesar cipher of shift 4 and then decrypt it.
E (5th letter) + 4 → I
X + 4 → B (X, Y, Z, A, B — wraps around)
A + 4 → E; M + 4 → Q
Ciphertext = IBEQ
Decrypt by shifting back 4: I → E, B → X, E → A, Q → M → EXAM
Q4. What is phishing? How can users protect themselves?
Phishing is a fraud where attackers send fake messages or websites that look real to steal passwords, OTPs or card details.
Signs: urgent tone, spelling mistakes, unknown links, requests for OTP or PIN.
Never share OTP/PIN; banks never ask for them.
Check the website address and the padlock (HTTPS) before entering details.
Use 2FA, keep software updated, report suspicious messages.
Q5. Explain firewalls and their types.
A firewall monitors and filters traffic between a trusted network and an untrusted one (the Internet) using rules.
Packet-filtering firewall: checks IP addresses, ports and protocols of each packet.
Stateful inspection firewall: tracks active connections and allows only valid replies.
Application-level gateway (proxy): filters at the application layer (e.g. web traffic).
Can be hardware (in routers) or software (on each computer, e.g. the OS firewall).
Exam tip
Learn the types of malware with one-line differences and one Indian cyber-law point; short notes on phishing and firewall are very common.