MH State Board All Notes Free5th to 12th & BA, BSc, B.Com 🔍

Computer Science संगणकशास्त्र

BSc Semester 6 · 10 chapters · 10 with notes

Chapters

  1. 10Software Engineering and SDLCNotes
  2. 11UML DiagramsNotes
  3. 12HTML and CSSNotes
  4. 13JavaScript BasicsNotes
  5. 14Python Programming BasicsNotes
  6. 15Java BasicsNotes
  7. 16Java GUI: AWT, Swing and Event HandlingNotes
  8. 17Finite Automata and Regular ExpressionsNotes
  9. 18Phases of a CompilerNotes
  10. 19Cyber Security BasicsNotes

BSc Semester 6 · Computer Science · Chapter 10

Software Engineering and SDLC

Quick summary

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).
  • SDLC phases: (1) feasibility study, (2) requirement analysis and specification (SRS), (3) design, (4) coding/implementation, (5) testing, (6) deployment, (7) maintenance.
  • 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.
  • Design tools: DFD (data flow diagram), ER diagram, flowcharts, structure charts, UML diagrams (use-case, class, sequence).
  • 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).
  • Maintenance types: corrective (fix bugs), adaptive (new environment), perfective (improve features), preventive.

Important terms

  • 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)
ModelBest whenDrawback
Waterfallrequirements clear, small projectlate changes costly
Prototyperequirements unclearmay encourage quick fixes
Spirallarge, high-risk projectcomplex, costly
Agilerequirements change oftenneeds 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.

  • Phases in sequence: requirements → design → coding → testing → deployment → maintenance.
  • Each phase's output is the next phase's input; documents at every stage.
  • Merits: simple, easy to manage, clear milestones.
  • Demerits: no working software until late; hard to go back; poor for changing requirements.
  • Diagram: steps drawn like a waterfall, top-left to bottom-right.

Q4. Explain the Spiral model.

  • Proposed by Barry Boehm (1986); combines iterative development with risk management.
  • Each loop has four quadrants: determine objectives, identify and resolve risks (prototypes), develop and test, plan the next iteration.
  • Radius of the spiral shows cost so far; angle shows progress.
  • Suitable for large and risky projects.
  • Drawback: needs risk-analysis expertise; costly for small projects.

Q5. Explain the levels of software testing.

  • Unit testing: each module/function tested alone, usually by developers.
  • Integration testing: modules combined and their interfaces tested (top-down, bottom-up).
  • System testing: complete system tested against SRS (functional, performance, security).
  • Acceptance testing: users check if it meets their needs; alpha and beta testing.
  • Regression testing: re-testing after changes to make sure nothing else broke.

Exam tip

Draw each SDLC model's diagram in your answer — examiners expect it. A comparison table of models fetches quick marks in short notes.

BSc Semester 6 · Computer Science · Chapter 11

UML Diagrams

Quick summary

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.
  • UML 2.x has 14 diagram types in two groups:
  • Structural (static): class, object, component, deployment, package, composite structure, profile.
  • 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

SymbolMeaning
+ / − / #Public / private / protected member
Hollow triangle arrowGeneralisation (inheritance)
Hollow diamondAggregation (has-a, weak)
Filled diamondComposition (strong ownership)
Dashed arrowDependency
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: − rollNo: int, − name: String; + enroll(c: Course), + getDetails()
  • Course: − code: String, − title: String, − credits: int; + getCredits()
  • Department: − name: String; + addCourse(c: Course)
  • 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.

BSc Semester 6 · Computer Science · Chapter 12

HTML and CSS

Quick summary

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>.
  • Link: <a href="page2.html">Next</a>. Image: <img src="photo.jpg" alt="text" width="200">.
  • 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

Common CSS properties: color, background-color, font-size, font-family, text-align, margin, padding, border, width, height, display.

A tiny page (tags shown with < >):

<!DOCTYPE html> <html><head><title>My Page</title></head> <body> <h1>Welcome</h1> <p class="note">Study daily.</p> </body></html>

5 important questions

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.

  • Total = width + 2 × padding + 2 × border + 2 × margin
  • = 300 + 2 × 10 + 2 × 2 + 2 × 15
  • = 300 + 20 + 4 + 30
  • = 354 px (with box-sizing: border-box the visible box would stay 300px)

Q4. Write HTML for a table with two columns, Name and Marks, and two student rows.

<table border="1"> <tr><th>Name</th><th>Marks</th></tr> <tr><td>Asha</td><td>78</td></tr> <tr><td>Rahul</td><td>85</td></tr> </table>
  • tr = row, th = heading cell (bold, centred), td = data cell.

Q5. Explain the three ways of adding CSS to HTML with examples.

  • Inline: style attribute on one element, e.g. <p style="color:red">; quick but hard to maintain.
  • Internal: CSS rules inside <style>…</style> in the head; good for one page.
  • External: rules in a .css file linked with <link rel="stylesheet" href="style.css">; one file styles many pages; best practice.
  • Priority: inline > internal/external (the later of these two wins when specificity is equal).

Exam tip

Practise writing small programs for a list, a table and a form by hand. Always close tags in the reverse order you opened them.

BSc Semester 6 · Computer Science · Chapter 13

JavaScript Basics

Quick summary

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>.
  • Output: document.write(), alert(), console.log(); input: prompt(), confirm().
  • 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

ExpressionResultReason
5 + "5""55"+ with a string joins
"5" * 210* converts to number
5 == "5"trueLoose equality converts type
5 === "5"falseStrict: types differ
typeof null"object"Old language quirk
10 / 0InfinityNo 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.

BSc Semester 6 · Computer Science · Chapter 14

Python Programming Basics

Quick summary

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.
  • range(start, stop, step) stops before 'stop': range(1, 5) gives 1, 2, 3, 4.
  • 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
TypeOrderedMutableDuplicatesExample
listyesyesyes[1, 2, 2]
tupleyesnoyes(1, 2)
setnoyesno{1, 2}
dictyes (3.7+)yeskeys 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.

Q2. Find the output: print(17 // 5, 17 % 5, 2 ** 4, 17 / 5)

17 // 5 = 3 (floor division), 17 % 5 = 2 (remainder), 2 ** 4 = 16, 17 / 5 = 3.4. Output: 3 2 16 3.4

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.
  • Add/update: d["marks"] = 78
  • Delete: del d["roll"] or d.pop("roll")
  • Loop: for k, v in d.items(): print(k, v)
  • Methods: keys(), values(), items(), update(), clear().

Exam tip

Indentation errors lose marks in written code too — keep each block indented by 4 spaces. Practise output questions on slicing and operators.

BSc Semester 6 · Computer Science · Chapter 15

Java Basics

Quick summary

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.
  • Access modifiers: private, default (package), protected, public.
  • 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.
  • JVM (जावा आभासी यंत्र) – virtual machine that runs Java bytecode.
  • 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).
  • A class can implement many interfaces.
interface Printable { void print(); } interface Showable { void show(); } class Doc implements Printable, Showable { public void print() { System.out.println("print"); } public void show() { System.out.println("show"); } }
  • Doc must define all methods of both interfaces.

Q5. Explain exception handling in Java with an example.

  • Exception = run-time error that disturbs normal flow.
  • try block holds risky code; catch handles the exception; finally always runs (closing files).
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.

BSc Semester 6 · Computer Science · Chapter 16

Java GUI: AWT, Swing and Event Handling

Quick summary

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.

Formulas

PointAWTSwing
Packagejava.awtjavax.swing
WeightHeavyweightLightweight
Look and feelDepends on OSPluggable, same on all OS
ComponentsFewerMany more (JTable, JTree)
ExampleButtonJButton
ListenerMethod(s)
ActionListeneractionPerformed(ActionEvent e)
ItemListeneritemStateChanged(ItemEvent e)
KeyListenerkeyPressed, keyReleased, keyTyped
MouseListenermouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited

5 important questions

Q1. Differentiate AWT and Swing.

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.

BSc Semester 6 · Computer Science · Chapter 17

Finite Automata and Regular Expressions

Quick summary

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ⁿ
RELanguage
(0 + 1)∗01Binary strings ending in 01
a(a + b)∗bStrings 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.

StateOn 0On 1
→ q0q1q0
q1q1q2
q2 (final)q1q0
  • 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 stateOn 0On 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.

BSc Semester 6 · Computer Science · Chapter 18

Phases of a Compiler

Quick summary

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.

Key points

  • Language-processing system: preprocessor → compiler → assembler → linker/loader → executable in memory.
  • 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):

PhaseOutput
Lexicalid1 = id2 + id3 × 60 (id1 = position, id2 = initial, id3 = rate in the symbol table)
SyntaxTree: = at root; left id1; right + with children id2 and (× with children id3, 60)
Semantic60 is an int, so it is converted: id3 × inttofloat(60)
Intermediatet1 = inttofloat(60); t2 = id3 × t1; t3 = id2 + t2; id1 = t3
Optimisationt1 = id3 × 60.0; id1 = id2 + t1
Code generationLDF R2, id3; MULF R2, R2, #60.0; LDF R1, id2; ADDF R1, R1, R2; STF id1, R1

5 important questions

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.

BSc Semester 6 · Computer Science · Chapter 19

Cyber Security Basics

Quick summary

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.

SymmetricAsymmetric
one shared secret keypublic + private key pair
fastslower
key sharing is a problempublic key can be shared openly
AES, DESRSA, 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.