KM-02 – Principles of Programming with
Java
NQF Level 4 – Comprehensive Learner Study Guide
22 Sessions | Detailed Notes | Corrected & Commented Code | How to Run Each Program
📘 How to use this guide
Each session follows the same structure:
1. Key Notes & Explanations
2. Worked Code Examples (with a comment on every line)
3. How to Run the Code (step-by-step)
4. Quick Summary Box
Session 1: KM-02-KT01 – Java Main Method with JVM
What is a Java Class?
A class is the blueprint for a Java program. Everything in Java lives inside a class. Think of a class
like a recipe — it describes what something is and what it can do.
Part What it means
public Anyone (including the JVM) can see and use this class
class Keyword that tells Java we are creating a class
ClassName The name you give your class (must match filename)
{} The class body — all code lives between these curly braces
The main() Method — Entry Point of Every Java Program
When you run a Java program, the JVM (Java Virtual Machine) looks for one specific method to start:
public static void main(String[] args). Without it, your program cannot run.
Keyword What it does
public JVM can call this method from outside the class
static No object needed — JVM calls it directly
void The method does not return any value
main The fixed name the JVM looks for
String[] args Holds any text you pass in when running from command line
Code Example 1 – Hello World
💡 What this program does
Prints the text 'Hello, World!' to the screen. This is always the first Java program beginners write.
// File: [Link]
// This is a single-line comment — Java ignores it
public class HelloWorld { // Declare a class named HelloWorld
// The file MUST be named [Link]
public static void main(String[] args) { // Entry point — JVM starts here
[Link]("Hello, World!"); // Print text + newline to console
} // End of main method
} // End of class
How to Run (Eclipse)
1. Open Eclipse → File → New → Java Project → give it a name.
2. Right-click the src folder → New → Class → type HelloWorld → tick 'public static void main' →
Finish.
3. Type (or paste) the code above.
4. Click the green ▶ Run button (or press Ctrl+F11).
5. Expected output in the Console tab: Hello, World!
How to Run (VS Code)
6. Open VS Code → File → Open Folder → choose your project folder.
7. Create a file named [Link] and paste the code.
8. Click 'Run' above the main method OR open a terminal and type:
javac [Link] // Compiles: creates [Link]
java HelloWorld // Runs the compiled program
How to Run (Command Line only)
// Step 1 — navigate to the folder containing [Link]
cd C:\Users\YourName\JavaProjects
// Step 2 — compile (convert .java source → .class bytecode)
javac [Link]
// Step 3 — run the bytecode with the JVM
java HelloWorld
// Output:
Hello, World!
Passing Arguments to main()
You can send data to your program when you run it. These are called command-line arguments and
they land in the args array.
// File: [Link]
public class GreetUser {
public static void main(String[] args) { // args stores command-line values
if ([Link] == 0) { // Check if no arguments were
given
[Link]("No name given!");
} else {
// args[0] is the first argument, args[1] the second, etc.
[Link]("Hello, " + args[0] + "!"); // Combine strings
}
}
}
// Run with: java GreetUser Alice
// Output: Hello, Alice!
📝 Quick Summary – Session 1
• A Java class is declared with: public class ClassName { }
• Every runnable Java program needs: public static void main(String[] args)
• javac compiles your .java file into bytecode (.class file)
• java runs the bytecode using the JVM
• Command-line arguments are received through the args[] array
Session 2: KM-02-KT02 – Introduction to Variables
What is a Variable?
A variable is a named storage location in memory. Think of it like a labelled box — you can put a
value inside, look at it, and change it.
Every variable in Java has three things:
• A data type (what kind of value it holds — int, String, boolean…)
• A name (what you call it — follow camelCase naming)
• A value (the actual data stored inside)
Variable Types in Java
Category Examples
Primitive int, double, boolean, char, byte, short, long, float
Reference String, arrays, objects (e.g. Student, ArrayList)
Enum Named constants: enum Day { MON, TUE, WED }
Variable Naming Rules
Rule Example
Start with a letter (not a digit) int age; ✓ int 1age; ✗
Use camelCase for variable names int studentAge; ✓ int student_age; ✗
Constants use ALL_CAPS with final int MAX_SCORE = 100;
underscores
No Java reserved words int class; ✗ (class is a keyword)
Code Example 2 – Declaring, Assigning & Reading Variables
💡 What this program does
Shows every type of variable operation: declare, assign, reassign, read, and print.
// File: [Link]
public class VariableDemo {
public static void main(String[] args) {
// --- DECLARE a variable (just reserve the box, no value yet) ---
int age; // declare an integer variable called age
// --- ASSIGN a value ---
age = 20; // put the number 20 into the box called age
// --- DECLARE and ASSIGN on one line (most common style) ---
double price = 49.99; // double holds decimal numbers
boolean isStudent = true; // boolean is either true or false
char grade = 'A'; // char holds a single character in single
quotes
String name = "Alice"; // String holds text in double quotes
// --- READ (print) the values ---
[Link]("Name: " + name); // + joins strings together
[Link]("Age: " + age);
[Link]("Price: R" + price);
[Link]("Grade: " + grade);
[Link]("Student? " + isStudent);
// --- UPDATE (reassign) a variable ---
age = 21; // the box now holds 21 instead of 20
[Link]("Next year age: " + age);
// --- CONSTANT: value can NEVER change after assignment ---
final int DAYS_IN_WEEK = 7; // final means this is a constant
[Link]("Days in a week: " + DAYS_IN_WEEK);
}
}
/* Expected Output:
Name: Alice
Age: 20
Price: R49.99
Grade: A
Student? true
Next year age: 21
Days in a week: 7
*/
How to Store Variables in Memory
Primitive variables (int, double, etc.) store their actual value directly in memory (stack). Reference
variables (String, arrays) store a memory address that points to the object stored elsewhere (heap).
📝 Quick Summary – Session 2
• Variables are named memory containers with a type, name, and value
• Use camelCase for names: studentAge, totalPrice
• Use ALL_CAPS for constants declared with final
• Primitives store values directly; reference types store addresses
• Uninitialized primitives default to 0, false, or null (if reference)
Session 3: KM-02-KT03 – Primitive Data Types & Alternatives
The 8 Primitive Data Types
Type Size / Range / Use
byte 8-bit | -128 to 127 | small integers, network data
short 16-bit | -32,768 to 32,767 | rarely used directly
int 32-bit | -2 billion to 2 billion | most common integer type
long 64-bit | very large integers | add L: long x = 100L;
float 32-bit decimal | 7 digits precision | add F: float f = 3.14F;
double 64-bit decimal | 15 digits precision | default for decimals
char 16-bit Unicode character | single quotes: char c = 'A';
boolean true or false only | used in conditions
Casting – Converting Between Types
Widening (safe, automatic): going from a smaller type to a larger type — Java does this for you.
Narrowing (risky, manual): going from a larger type to a smaller — you must explicitly cast using
(type).
// File: [Link]
public class CastingDemo {
public static void main(String[] args) {
// WIDENING (implicit) — Java automatically converts int → double
int intVal = 100;
double doubleVal = intVal; // No cast needed — safe widening
[Link](doubleVal); // prints 100.0
// NARROWING (explicit) — must cast manually, data may be lost
double pi = 3.14159;
int piInt = (int) pi; // (int) forces conversion — drops decimals
[Link](piInt); // prints 3 (0.14159 is lost!)
// Post-increment vs Pre-increment
int x = 5;
int y = x++; // y gets current value (5), THEN x becomes 6
int z = ++x; // x becomes 7 FIRST, then z gets 7
[Link]("y=" + y + " x=" + x + " z=" + z); // y=5 x=7 z=7
}
}
BigDecimal – For Precise Calculations
Normal floats and doubles have rounding errors due to binary representation. For financial
calculations, always use BigDecimal.
// File: [Link]
import [Link]; // must import this class first
public class BigDecimalDemo {
public static void main(String[] args) {
// Create BigDecimal from strings (never from doubles — keeps precision)
BigDecimal principal = new BigDecimal("1000"); // R1000
BigDecimal rate = new BigDecimal("5"); // 5 percent
BigDecimal time = new BigDecimal("2"); // 2 years
// Simple Interest = (Principal × Rate × Time) / 100
BigDecimal interest = principal
.multiply(rate) // 1000 × 5 = 5000
.multiply(time) // 5000 × 2 = 10000
.divide(new BigDecimal("100")); // 10000 ÷ 100 =
100
[Link]("Simple Interest: R" + interest); // R100
}
}
Boolean Data Type & Operators
Operator Meaning / Example
== Equal to: 5 == 5 → true
!= Not equal: 5 != 3 → true
>/< Greater / Less than
>= / <= Greater-or-equal / Less-or-equal
&& AND: both must be true — short-circuits on first false
|| OR: at least one true — short-circuits on first true
! NOT: reverses the boolean !true → false
📝 Quick Summary – Session 3
• 8 primitive types: byte, short, int, long, float, double, char, boolean
• Widening cast is automatic; narrowing cast requires (type) and loses data
• Use BigDecimal for any money / financial calculations
• && and || short-circuit (stop checking once result is known)
Session 4: KM-02-KT04 – Arrays and ArrayLists
Arrays – Fixed-Size Collections
An array stores multiple values of the SAME type in a single variable. The size is fixed when you
create it — you cannot add or remove elements later.
// File: [Link]
import [Link]; // needed for [Link]() and [Link]()
public class ArrayDemo {
public static void main(String[] args) {
// --- Declare and initialise an array with values ---
int[] scores = {85, 92, 78, 90, 88}; // array of 5 integers
// --- Access elements using index (starts at 0, not 1) ---
[Link]("First score: " + scores[0]); // 85
[Link]("Last score: " + scores[4]); // 88
// --- Get length ---
[Link]("Number of scores: " + [Link]); // 5
// --- Loop through every element ---
int total = 0;
for (int i = 0; i < [Link]; i++) { // i goes from 0 to 4
total += scores[i]; // add each score to total
}
double average = (double) total / [Link]; // cast to get decimal
[Link]("Average: " + average); // 86.6
// --- Sort the array in ascending order ---
[Link](scores);
[Link]([Link](scores)); // [78, 85, 88, 90, 92]
}
}
ArrayList – Flexible, Resizable Collections
ArrayList is a dynamic array — it can grow and shrink as you add/remove elements. It stores objects,
so you use Integer instead of int, etc.
// File: [Link]
import [Link]; // import ArrayList class
import [Link]; // import for [Link]()
public class ArrayListDemo {
public static void main(String[] args) {
// Create an ArrayList that holds String objects
ArrayList<String> names = new ArrayList<>(); // <String> is the type
// --- Add elements ---
[Link]("Alice"); // adds to the end
[Link]("Bob");
[Link]("Charlie");
// --- Access by index ---
[Link]([Link](0)); // Alice (index 0)
// --- Check size ---
[Link]("Size: " + [Link]()); // 3
// --- Remove an element ---
[Link]("Bob"); // remove by value
// OR: [Link](1); — remove by index
// --- Loop through with for-each ---
for (String name : names) { // reads: 'for each name in names'
[Link](name);
}
// --- Sort alphabetically ---
[Link](names);
}
}
Feature Array vs ArrayList
Size Fixed (cannot change) | Dynamic (grows/shrinks)
Type Can hold primitives | Only objects (Integer, String…)
Length/Size [Link] | [Link]()
Access array[0] | [Link](0)
Add element Not possible | [Link](value)
📝 Quick Summary – Session 4
• Arrays have a fixed size; use array[i] to access elements; index starts at 0
• ArrayList is dynamic; use add(), remove(), get(), size()
• Use [Link]() for arrays; [Link]() for ArrayLists
• Use [Link]() to set all elements to the same value
Session 5: KM-02-KT05 – Array of Objects
What is an Array of Objects?
Instead of storing primitive values, an array can store references to objects. Each element points to
an instance of a class.
// File: [Link] — defines what a Student looks like
public class Student {
private String name; // field: stores the student's name
private int age; // field: stores the student's age
// Constructor — called when we create a new Student object
public Student(String name, int age) {
[Link] = name; // '[Link]' refers to the field, 'name' is the
parameter
[Link] = age;
}
// Getter methods — allow reading private fields
public String getName() { return name; }
public int getAge() { return age; }
}
// File: [Link]
public class ArrayOfObjectsDemo {
public static void main(String[] args) {
// Create an array that can hold 3 Student objects
Student[] students = new Student[3];
// Populate each slot with a new Student object
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Charlie", 21);
// Loop through and print each student's details
for (int i = 0; i < [Link]; i++) {
[Link](students[i].getName() + " is " +
students[i].getAge());
}
}
}
// Output:
// Alice is 20
// Bob is 22
// Charlie is 21
📝 Quick Summary – Session 5
• Array of objects stores references (memory addresses) to class instances
• You must 'new' each object before using it — null slots crash the program
• Access object methods with dot notation: students[0].getName()
Session 6: KM-02-KT06 – ArrayList Methods
// File: [Link]
import [Link];
import [Link];
public class ArrayListMethods {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
[Link](5); [Link](2); [Link](9); [Link](1);
// contains() — check if a value exists
[Link]([Link](9)); // true
// indexOf() — find position of a value (-1 if not found)
[Link]([Link](2)); // 1
// set() — replace a value at an index
[Link](0, 10); // replace index 0 (was 5) with 10
// [Link]() — sorts ascending
[Link](nums); // [1, 2, 9, 10]
[Link](nums);
// [Link]() and min()
[Link]([Link](nums)); // 10
[Link]([Link](nums)); // 1
// clear() — remove all elements
[Link]();
[Link]([Link]()); // true
}
}
📝 Quick Summary – Session 6
• add(), remove(), get(), set(), size(), contains(), indexOf()
• [Link](), [Link](), [Link]()
• clear() removes all; isEmpty() checks if list has no elements
Session 7: KM-02-KT07 – Reference Types in Java
Primitive vs Reference Types
Primitive types (int, char, etc.) store actual values. Reference types store a memory address pointing
to an object on the heap.
// File: [Link]
public class ReferenceTypeDemo {
public static void main(String[] args) {
// PRIMITIVE — each variable has its own copy
int a = 10;
int b = a; // b gets a copy of 10
b = 20; // changing b does NOT affect a
[Link]("a=" + a + " b=" + b); // a=10 b=20
// REFERENCE — both variables point to the SAME object
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1; // arr2 points to the SAME array as arr1
arr2[0] = 99; // changing arr2 ALSO changes arr1!
[Link](arr1[0]); // 99 — arr1 is also changed
// NULL — a reference that points to nothing
String s = null; // s holds no object yet
// [Link]() would throw NullPointerException — check first!
if (s != null) {
[Link]([Link]());
}
}
}
⚠ Warning – NullPointerException
The most common Java crash! Happens when you try to use a reference variable that is null.
Always check: if (obj != null) before calling methods on an object.
📝 Quick Summary – Session 7
• Primitive variables store values; reference variables store addresses
• When you assign one reference to another, they SHARE the same object
• null means 'no object' — calling methods on null causes NullPointerException
Session 8: KM-02-KT08 – Java Strings
Key String Facts
• Strings are objects of class String — not a primitive type.
• Strings are IMMUTABLE — once created, the content cannot change. Any 'change' creates a NEW
string.
• String literals go into a string pool for memory efficiency.
Code Example – String Methods
// File: [Link]
public class StringDemo {
public static void main(String[] args) {
String text = "Hello, World!";
// length() — number of characters
[Link]([Link]()); // 13
// charAt(index) — character at a position
[Link]([Link](0)); // H
// substring(start, end) — part of the string (end is exclusive)
[Link]([Link](0, 5)); // Hello
// toUpperCase() / toLowerCase()
[Link]([Link]()); // HELLO, WORLD!
// replace(old, new)
[Link]([Link]("World", "Java")); // Hello, Java!
// contains() — check if substring exists
[Link]([Link]("World")); // true
// trim() — remove leading/trailing spaces
String padded = " hello ";
[Link]([Link]()); // hello
// COMPARE strings — use .equals(), NOT ==
String s1 = "Java";
String s2 = "Java";
[Link]([Link](s2)); // true ✓ correct
[Link]([Link](s2)); // true (ignores case)
// Escape characters in strings
[Link]("Line1\nLine2"); // \n = new line
[Link]("Col1\tCol2"); // \t = tab
[Link]("She said \"Hi\""); // \" = quote inside string
}
}
Escape Meaning
\n New line
\t Horizontal tab
\" Double quote inside a string
\' Single quote
\\ Backslash itself
📝 Quick Summary – Session 8
• Strings are immutable objects — use methods like replace() to get modified copies
• NEVER use == to compare strings — always use .equals()
• String Pool: identical literals share the same object to save memory
• StringBuilder is more efficient for building strings in a loop
Session 9–12: Classes, Nested Classes, Abstract Classes & Wrapper
Classes
Session 9 – Java Classes
A class is the blueprint. An object is the real thing built from that blueprint. Classes bundle data
(fields) and behaviour (methods) together — this is called Encapsulation.
// File: [Link]
public class BankAccount {
// Fields (state) — private means only this class can access them
private String owner;
private double balance;
// Constructor — runs when you 'new' a BankAccount
public BankAccount(String owner, double initialBalance) {
[Link] = owner;
[Link] = initialBalance;
}
// Method — deposit money
public void deposit(double amount) {
if (amount > 0) { // only allow positive amounts
balance += amount; // balance = balance + amount
}
}
// Method — withdraw money
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) { // can't withdraw more than
balance
balance -= amount;
} else {
[Link]("Insufficient funds!");
}
}
// Getter — allow reading the private balance
public double getBalance() { return balance; }
// toString — what prints when you do [Link](account)
public String toString() {
return owner + "'s balance: R" + balance;
}
}
// File: [Link]
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Alice", 1000.0); // create object
[Link](500);
[Link](200);
[Link](acc); // calls toString()
}
}
// Output: Alice's balance: R1300.0
Session 10 – Nested Classes
Type When to use
Static nested class Helper class that doesn't need outer class instance
Inner class (non-static) Needs access to instance fields of outer class
Local class Defined inside a method; only usable there
Anonymous class One-off class created and used inline (no name)
Session 11 – Abstract Classes
An abstract class is a class that CANNOT be instantiated directly — it is a template. It can have
abstract methods (no body) that subclasses MUST implement.
// File: [Link] — abstract class
public abstract class Shape {
// Abstract method — no body, subclasses must provide the implementation
public abstract double calculateArea();
// Regular method — shared by all shapes
public void describe() {
[Link]("This shape has area: " + calculateArea());
}
}
// File: [Link] — extends the abstract class
public class Circle extends Shape {
private double radius;
public Circle(double radius) { [Link] = radius; }
// Must implement the abstract method
public double calculateArea() {
return [Link] * radius * radius; // π r²
}
}
// Usage:
Circle c = new Circle(5);
[Link](); // This shape has area: 78.539...
Session 12 – Wrapper Classes
Every primitive type has a matching Wrapper class that wraps it as an object. Needed for ArrayLists,
generics, and utility methods.
Primitive Wrapper Class
int Integer
double Double
char Character
boolean Boolean
// Autoboxing: int → Integer (automatic)
ArrayList<Integer> list = new ArrayList<>();
[Link](42); // Java automatically boxes 42 into Integer(42)
// Unboxing: Integer → int (automatic)
int val = [Link](0); // Integer unboxed back to int
// Useful Integer methods
int parsed = [Link]("123"); // convert String to int
String str = [Link](456); // convert int to String
[Link](Integer.MAX_VALUE); // 2147483647
📝 Quick Summary – Sessions 9–12
• Classes bundle fields + methods; use private fields with public getters/setters
• Abstract classes define templates; subclasses must implement abstract methods
• Wrapper classes wrap primitives as objects for use in collections
• Autoboxing/unboxing automatically converts between int ↔ Integer
Session 13: KM-02-KT13 – Java Date and Time
// File: [Link]
import [Link]; // date only (no time)
import [Link]; // time only (no date)
import [Link]; // both date and time
import [Link]; // for custom formatting
public class DateTimeDemo {
public static void main(String[] args) {
// Today's date
LocalDate today = [Link]();
[Link]("Today: " + today); // 2024-06-15
// Create a specific date
LocalDate birthday = [Link](2000, 3, 25); // year, month, day
[Link]("Birthday: " + birthday);
// Current time
LocalTime now = [Link]();
[Link]("Time: " + now); // 10:30:45.123
// Date and time together
LocalDateTime dateTime = [Link]();
// Format the date into a readable pattern
DateTimeFormatter fmt = [Link]("dd/MM/yyyy");
[Link]("Formatted: " + [Link](fmt)); // 15/06/2024
// Compare dates
LocalDate futureDate = [Link](2025, 12, 31);
[Link]([Link](futureDate)); // true
}
}
📝 Quick Summary – Session 13
• Use [Link] package (Java 8+) — much better than old Date class
• LocalDate = date only | LocalTime = time only | LocalDateTime = both
• DateTimeFormatter lets you display dates in any pattern
Session 14: KM-02-KT14 – Conditionals: if, else, else if
// File: [Link]
public class ConditionalDemo {
public static void main(String[] args) {
int score = 75;
// IF — only runs if condition is true
if (score >= 90) {
[Link]("Grade: A");
}
// ELSE IF — checked only if the above was false
else if (score >= 75) {
[Link]("Grade: B"); // ← this runs
}
else if (score >= 60) {
[Link]("Grade: C");
}
// ELSE — runs if NONE of the above were true
else {
[Link]("Grade: F");
}
// SWITCH — cleaner when comparing one variable to many fixed values
String day = "Monday";
switch (day) {
case "Saturday":
case "Sunday":
[Link]("Weekend!");
break; // stop checking more cases
default:
[Link]("Weekday.");
}
// TERNARY operator — shortcut for simple if/else
String result = (score >= 50) ? "Pass" : "Fail"; // condition ?
trueVal : falseVal
[Link](result); // Pass
}
}
📝 Quick Summary – Session 14
• if / else if / else: chains of conditions tested top-to-bottom
• switch: best when one variable has many fixed possible values
• Ternary: x = (condition) ? valueIfTrue : valueIfFalse
Session 15: KM-02-KT15 – Loops in Java
// File: [Link]
public class LoopsDemo {
public static void main(String[] args) {
// --- FOR loop — use when you know how many times to repeat ---
[Link]("FOR loop:");
for (int i = 1; i <= 5; i++) { // init; condition; update
[Link](i + " "); // print without newline
}
[Link](); // newline after loop
// --- WHILE loop — use when you don't know exact iterations ---
[Link]("WHILE loop:");
int count = 1;
while (count <= 5) { // keep going while condition is true
[Link](count + " ");
count++; // IMPORTANT: always update or loop runs
forever!
}
[Link]();
// --- DO-WHILE — runs at least once, then checks condition ---
[Link]("DO-WHILE:");
int x = 1;
do {
[Link](x + " ");
x++;
} while (x <= 5); // condition checked AFTER the body
[Link]();
// --- FOR-EACH — cleanest way to loop through arrays/lists ---
int[] nums = {10, 20, 30, 40};
for (int num : nums) { // 'for each num in nums'
[Link](num + " ");
}
[Link]();
// --- BREAK — exit the loop early ---
for (int i = 0; i < 10; i++) {
if (i == 5) break; // stop when i reaches 5
[Link](i + " "); // prints: 0 1 2 3 4
}
// --- CONTINUE — skip the current iteration ---
for (int i = 0; i < 6; i++) {
if (i % 2 == 0) continue; // skip even numbers
[Link](i + " "); // prints: 1 3 5
}
}
}
📝 Quick Summary – Session 15
• for: best when count is known. for(init; condition; update)
• while: best when condition drives the loop
• do-while: always runs at least once
• for-each: cleanest loop for arrays and collections
• break exits a loop; continue skips to the next iteration
Session 16: KM-02-KT16 – Java Math Class
// File: [Link]
public class MathDemo {
public static void main(String[] args) {
// [Link]() — absolute value (removes negative sign)
[Link]([Link](-15)); // 15
// [Link]() / [Link]() — largest / smallest of two values
[Link]([Link](10, 20)); // 20
[Link]([Link](10, 20)); // 10
// [Link](base, exponent) — power calculation
[Link]([Link](2, 10)); // 1024.0 (2 to the power of 10)
// [Link]() — square root
[Link]([Link](144)); // 12.0
// [Link]() — round to nearest integer
[Link]([Link](4.6)); // 5
[Link]([Link](4.4)); // 4
// [Link]() / [Link]() — round down / round up
[Link]([Link](4.9)); // 4.0
[Link]([Link](4.1)); // 5.0
// [Link]() — random double between 0.0 (inclusive) and 1.0
(exclusive)
double rand = [Link]();
int randInt = (int)([Link]() * 100); // random int 0–99
[Link](randInt);
// [Link] — the constant π
[Link]([Link]); // 3.141592653589793
}
}
📝 Quick Summary – Session 16
• Math class is built-in — no import needed
• All Math methods are static: call with [Link]()
• [Link]() returns 0.0 to <1.0; multiply and cast to get integers
Session 17: KM-02-KT17 – Algorithms in Java
What is an Algorithm?
An algorithm is a step-by-step set of instructions to solve a problem. Good algorithms are: correct,
efficient, and readable.
// File: [Link] — Linear Search + Bubble Sort
public class SearchSortDemo {
// LINEAR SEARCH — check each element one by one
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < [Link]; i++) {
if (arr[i] == target) return i; // found! return index
}
return -1; // not found
}
// BUBBLE SORT — repeatedly swap adjacent elements if in wrong order
public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) { // outer pass
for (int j = 0; j < n - i - 1; j++) { // inner comparison
if (arr[j] > arr[j + 1]) { // out of order?
int temp = arr[j]; // store arr[j] temporarily
arr[j] = arr[j+1]; // move smaller one left
arr[j+1] = temp; // place larger one right
}
}
}
}
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22};
bubbleSort(data);
for (int d : data) [Link](d + " "); // 12 22 25 34 64
[Link]();
[Link](linearSearch(data, 25)); // 2 (index of 25)
}
}
📝 Quick Summary – Session 17
• Algorithm = step-by-step instructions to solve a problem
• Linear Search: O(n) — checks every element; simple but slow for large data
• Bubble Sort: O(n²) — simple comparison sort; not efficient for large data
• Java's built-in [Link]() uses highly optimised algorithms — prefer it
Session 18: KM-02-KT18 – Modulus Operator
What Does % Do?
The modulus operator (%) gives you the REMAINDER after integer division. 17 % 5 = 2 because 17
÷ 5 = 3 remainder 2.
// File: [Link]
public class ModulusDemo {
public static void main(String[] args) {
// Basic usage
[Link](17 % 5); // 2 (17 ÷ 5 = 3 remainder 2)
[Link](10 % 2); // 0 (10 is evenly divisible by 2)
[Link](15 % 4); // 3
// --- Use case 1: Check even or odd ---
int n = 7;
if (n % 2 == 0) {
[Link](n + " is even");
} else {
[Link](n + " is odd"); // 7 is odd
}
// --- Use case 2: Cycle through values (wrap around) ---
// Useful for circular arrays, game turns, clock faces
for (int i = 0; i < 10; i++) {
[Link]((i % 3) + " "); // 0 1 2 0 1 2 0 1 2 0
}
[Link]();
// --- Use case 3: Check if year is a leap year ---
int year = 2024;
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
[Link](year + " is leap year: " + isLeap); // true
}
}
📝 Quick Summary – Session 18
• % returns the remainder: 17 % 5 = 2
• Even/odd check: if (n % 2 == 0) → even
• Cycling: i % n wraps values back to 0 — useful for circular logic
Session 19: KM-02-KT19 – Introduction to Threads & Concurrency
What is a Thread?
A thread is a single path of execution within a program. Multithreading means running multiple
threads simultaneously — allowing tasks to happen at the same time.
// File: [Link]
// Method 1: Extend Thread class
class MyThread extends Thread {
private String taskName;
public MyThread(String name) {
[Link] = name;
}
// Override run() — this is what the thread will do
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](taskName + " step " + i);
try {
[Link](500); // pause for 500 milliseconds
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-A");
MyThread t2 = new MyThread("Thread-B");
[Link](); // start() creates a new thread and calls run()
[Link](); // both run CONCURRENTLY (interleaved output)
}
}
// Output order is not guaranteed — depends on JVM scheduling
Using ExecutorService (Preferred Modern Approach)
import [Link];
import [Link];
ExecutorService executor = [Link](2); // pool of 2 threads
[Link](() -> [Link]("Task 1 running"));
[Link](() -> [Link]("Task 2 running"));
[Link](); // no new tasks, wait for current ones to finish
⚠ Key Concepts – Threads
Race Condition: two threads change shared data at the same time → unpredictable results.
Deadlock: Thread A waits for Thread B, and Thread B waits for Thread A — both stuck forever.
Synchronization (synchronized keyword): ensures only one thread accesses a block at a time.
📝 Quick Summary – Session 19
• Threads allow parallel execution inside a program
• Extend Thread or implement Runnable; call start() (not run())
• Use ExecutorService for production code — manages thread pools
• Protect shared data with the synchronized keyword
Session 20: KM-02-KT20 – Exception Handling in Java
What is an Exception?
An exception is an unexpected event during runtime that disrupts the program. Java's try-catch
mechanism lets you handle errors gracefully instead of crashing.
Type Description
Checked Exception Must be handled (try-catch) or declared (throws). E.g.
IOException
Unchecked/Runtime Exception Programming errors. E.g. NullPointerException,
ArrayIndexOutOfBoundsException
Error Severe JVM problems — do NOT catch. E.g.
OutOfMemoryError
// File: [Link]
public class ExceptionDemo {
public static void main(String[] args) {
// --- Basic try-catch ---
try {
int result = 10 / 0; // ArithmeticException: divide by zero
[Link](result); // this line is skipped
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
}
// --- Multiple catch blocks ---
try {
int[] arr = new int[3];
arr[10] = 5; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of range!");
} catch (Exception e) {
[Link]("Some other error: " + [Link]());
} finally {
// finally ALWAYS runs — use for cleanup (close files, etc.)
[Link]("Cleanup done.");
}
// --- Throwing your own exception ---
try {
checkAge(-5); // will throw exception
} catch (IllegalArgumentException e) {
[Link]("Error: " + [Link]());
}
}
// Custom validation method that throws exception
public static void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative: " + age);
}
[Link]("Age is valid: " + age);
}
}
/* Output:
Cannot divide by zero: / by zero
Array index out of range!
Cleanup done.
Error: Age cannot be negative: -5
*/
📝 Quick Summary – Session 20
• try: code that might throw an exception
• catch: handles a specific exception type
• finally: always runs — good for closing resources
• throw: manually create and throw an exception
• Checked exceptions must be handled; RuntimeExceptions are optional
Session 21: KM-02-KT21 – File System and Directories in Java
Working with Files in Java
Java's [Link] and [Link] packages let you create, read, write, and delete files and directories.
Always wrap file operations in try-catch because files can fail (not found, no permission, disk full).
// File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FileDemo {
public static void main(String[] args) {
// --- CREATE a file ---
File myFile = new File("[Link]"); // just a reference, not created
yet
try {
if ([Link]()) { // createNewFile() actually
makes it
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("Error creating file: " + [Link]());
}
// --- WRITE to the file ---
try {
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello from Java!\n"); // write a line
[Link]("This is line 2.\n");
[Link](); // IMPORTANT: always close after writing
[Link]("Written successfully.");
} catch (IOException e) {
[Link]("Error writing: " + [Link]());
}
// --- READ from the file ---
try {
BufferedReader reader = new BufferedReader(new
FileReader("[Link]"));
String line;
// readLine() returns null when there are no more lines
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch (IOException e) {
[Link]("Error reading: " + [Link]());
}
// --- FILE INFO ---
[Link]("Exists: " + [Link]());
[Link]("Size: " + [Link]() + " bytes");
[Link]("Path: " + [Link]());
// --- DIRECTORIES ---
File dir = new File("myFolder");
[Link](); // create a single directory
// [Link](); — creates parent directories too
// --- DELETE the file ---
[Link]();
[Link]("Deleted: " + ![Link]());
}
}
📝 Quick Summary – Session 21
• File class: represents a file/directory reference (doesn't read/write itself)
• FileWriter + close(): write text to a file
• BufferedReader + FileReader: efficient line-by-line reading
• Always close() file streams — or better, use try-with-resources
• Wrap file code in try-catch IOException
Session 22: KM-02-KT22 – Programming Life Cycle (SDLC)
What is the SDLC?
The Software Development Life Cycle (SDLC) is the structured process a team follows to build
software — from the first idea all the way to retirement.
Stage What happens
1. Requirements Gathering Understand what the client/user needs; document
everything
2. Planning & Feasibility Define scope, budget, timeline, and risks
3. System Design Design architecture, database, UI wireframes
4. Implementation (Coding) Write the actual code following the design
5. Testing Unit tests, integration tests, bug fixing
6. Deployment Release to production / deliver to users
7. Maintenance & Support Fix bugs, add features, support users
8. Retirement Decommission when obsolete; migrate data
Key SDLC Principles
• Plan before you code — changing requirements mid-build is expensive.
• Iterate: build small pieces, test, get feedback, improve.
• Document everything — future developers (including you!) need it.
• Use version control (Git) throughout — never lose your work.
• Test at every stage — not just at the end.
📝 Quick Summary – Session 22
• SDLC gives structure to software projects — reduces wasted effort
• The 8 core stages: Gather → Plan → Design → Code → Test → Deploy → Maintain → Retire
• Iterative models (Agile) deliver working software in short sprints
• Good documentation, version control, and testing are non-negotiable
FINAL QUICK REFERENCE – Common Java Errors & Fixes
Error Most likely cause & fix
NullPointerException Used a reference that is null. Check: if (obj != null) first
ArrayIndexOutOfBoundsException Accessed index ≥ [Link]. Check loop bounds.
ClassCastException Cast to wrong type. Use instanceof before casting.
ArithmeticException Divided by zero. Add a check: if (divisor != 0)
StackOverflowError Infinite recursion. Ensure base case in recursive
methods.
FileNotFoundException File path is wrong or file does not exist.
NumberFormatException Tried to parse a non-numeric string. E.g.
[Link]("abc")
Cannot find symbol Typo in variable/method name, or not imported.
Java Program Template — Copy & Use
// File: [Link]
// Author: [Your Name]
// Date: [Date]
// Purpose: [What this program does]
public class MyProgram { // filename must match class name
public static void main(String[] args) {
// Your code goes here
[Link]("Program started!");
}
}
// To compile: javac [Link]
// To run: java MyProgram