JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
JAVA
Complete Study Notes
Grade 12 Information Technology | Practical Exam
Aligned to IEB SAGS | OOP · Algorithms · File I/O · Data Structures
📋 Topics covered: Variables & Data Types • Operators • Control Structures • Methods • Arrays •
OOP: Classes, Constructors, Getters/Setters, toString • Inheritance • Polymorphism • Encapsulation •
ArrayList • File I/O • Exception Handling • String Methods • Math Methods • Algorithms: Search & Sort
• Common Mistakes
1. Variables, Data Types & Constants
Every variable must be declared with a type before use. Java is strongly typed.
Primitive Data Types
Type Size Range / Use Example Declaration
int 32-bit Whole numbers –2,147,483,648 int age = 17;
to 2,147,483,647
double 64-bit Decimal numbers (most precise) double price = 9.99;
float 32-bit Decimal (less precise, add f suffix) float temp = 36.5f;
boolean 1-bit true or false only boolean passed = true;
char 16-bit A single character in single quotes char grade = 'A';
long 64-bit Very large whole numbers (add L long pop = 8000000000L;
suffix)
byte 8-bit Small integers -128 to 127 byte b = 100;
short 16-bit Medium integers -32768 to 32767 short s = 1000;
String (Reference Type)
String name = "John"; // String with capital S — it's a class, not
primitive
String empty = ""; // Empty string
String combined = "Hello" + " " + name; // Concatenation with +
Constants — use final keyword
final double VAT = 0.15; // Cannot be changed after declaration
final int MAX_SIZE = 100; // Convention: ALL_CAPS for constants
Type Casting — converting between types
// Implicit (widening) — safe, done automatically
int x = 5;
double d = x; // int → double, no data loss
Page 1 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
// Explicit (narrowing) — must cast manually, may lose data
double pi = 3.14;
int approx = (int) pi; // approx = 3, decimal part lost
// String to number
int num = [Link]("42");
double val = [Link]("3.14");
// Number to String
String s = [Link](42);
String s2 = 42 + ""; // Quick trick using concatenation
⚠️ Common Mistake: [Link]() throws a NumberFormatException if the string is not a valid
number. Always use try-catch when parsing user input.
2. Operators
Arithmetic Operators
Operator Meaning Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division (int/int = int) 7/2 3 (truncated!)
% Modulus (remainder) 7%2 1
++ Increment by 1 x++ or ++x x=x+1
-- Decrement by 1 x-- or --x x=x-1
⚠️ Integer Division Trap: 7 / 2 gives 3, NOT 3.5. To get 3.5 you must use 7.0 / 2 or (double)7 / 2.
Comparison Operators
Operator Meaning Example
== Equal to age == 18
!= Not equal to grade != 'F'
> Greater than score > 50
< Less than price < 100
>= Greater than or equal marks >= 75
<= Less than or equal count <= 10
Logical Operators
Operator Meaning Example
&& AND — both must be true age >= 18 && age <= 65
|| OR — at least one must be true grade == 'A' || grade == 'B'
! NOT — reverses the boolean !passed
📝 String Comparison: Never use == to compare Strings. Use .equals() or .equalsIgnoreCase(). ==
compares memory addresses, not the actual content.
Page 2 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
// WRONG
if (name == "John") { }
// CORRECT
if ([Link]("John")) { }
if ([Link]("john")) { } // case-insensitive
Page 3 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
3. Control Structures
if / else if / else
if (mark >= 75) {
[Link]("Distinction");
} else if (mark >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}
switch Statement — use for discrete values
switch (grade) {
case 'A': [Link]("Excellent"); break;
case 'B': [Link]("Good"); break;
case 'C': [Link]("Average"); break;
default: [Link]("Below average");
}
⚠️ Always include break: Without break, execution falls through to the next case. This is a very common
bug.
for Loop — use when you know how many times to repeat
for (int i = 0; i < 5; i++) {
[Link]("Count: " + i); // prints 0,1,2,3,4
}
// Loop backwards
for (int i = 10; i >= 0; i--) {
[Link](i);
}
// Enhanced for loop (for-each) — arrays and ArrayLists
for (int num : numbers) {
[Link](num);
}
while Loop — use when you don't know how many iterations
int count = 0;
while (count < 10) {
[Link](count);
count++; // MUST update the variable or infinite loop!
}
do-while Loop — always runs at least once
int num;
do {
[Link]("Enter a positive number: ");
num = [Link]();
} while (num <= 0); // keeps asking until positive number entered
Page 4 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
Nested Loops
// Multiplication table — outer loop = rows, inner = columns
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link](i * j + "\t");
}
[Link](); // new line after each row
}
4. Methods (Subprograms)
Methods break code into reusable blocks. The SAGS requires you to use methods with parameters and return
values.
Method Structure
// accessModifier returnType methodName(parameters) {
// method body
// return value; (only if returnType is not void)
// }
// Void method — does something, returns nothing
public static void printGreeting(String name) {
[Link]("Hello, " + name + "!");
}
// Typed method — returns a value
public static double calculateVAT(double price) {
return price * 0.15;
}
// Method with multiple parameters
public static double calcAverage(int a, int b, int c) {
return (a + b + c) / 3.0;
}
Calling Methods
// In main or another method:
printGreeting("Sipho"); // void — just call it
double vat = calculateVAT(100.0); // store the returned value
[Link]("VAT: " + vat);
double avg = calcAverage(70, 85, 90);
[Link]("Average: " + avg);
Method Overloading — same name, different parameters
public static int add(int a, int b) {
return a + b;
Page 5 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
}
public static double add(double a, double b) {
return a + b;
}
// Java decides which version to call based on the argument types
📝 static keyword: Use public static for all methods in the main class (the class that contains main). You
only drop static when working inside your own OOP classes.
Page 6 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
5. Arrays
Arrays store multiple values of the same type. Size is fixed once declared.
Declaring and Initialising
// Declare then assign
int[] scores = new int[5]; // 5 slots, all default to 0
scores[0] = 85; scores[1] = 72;
// Declare and initialise at once
String[] names = {"Sipho", "Lerato", "James"};
double[] prices = new double[]{9.99, 14.50, 3.25};
// Access elements — index starts at 0
[Link](names[0]); // Sipho
[Link]([Link]); // 3 — number of elements
Looping through an Array
// Standard for loop — when you need the index
for (int i = 0; i < [Link]; i++) {
[Link]("Score " + i + ": " + scores[i]);
}
// Enhanced for loop — when you just need each value
for (int score : scores) {
[Link](score);
}
Common Array Algorithms
Find the maximum value
int max = arr[0]; // assume first is largest
for (int i = 1; i < [Link]; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
[Link]("Max: " + max);
Find the minimum value
int min = arr[0];
for (int i = 1; i < [Link]; i++) {
if (arr[i] < min) min = arr[i];
}
Calculate the sum and average
int sum = 0;
for (int val : arr) {
sum += val; // shorthand for sum = sum + val
}
Page 7 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
double average = (double) sum / [Link];
Count occurrences
int count = 0;
for (int val : arr) {
if (val > 50) count++;
}
2D Arrays (Arrays of Arrays)
int[][] grid = new int[3][4]; // 3 rows, 4 columns
grid[0][0] = 1; // row 0, column 0
// Initialise with values
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
// Loop through 2D array
for (int row = 0; row < [Link]; row++) {
for (int col = 0; col < matrix[row].length; col++) {
[Link](matrix[row][col] + "\t");
}
[Link]();
}
6. String Methods
Method What it does Example Result
length() Number of characters "Hello".length() 5
charAt(i) Character at index i "Hello".charAt(1) 'e'
substring(s) From index s to end "Hello".substring(2) "llo"
substring(s,e) From index s up to (not "Hello".substring(1,4) "ell"
incl.) e
indexOf(s) First index of substring (-1 if "Hello".indexOf("ll") 2
not found)
toUpperCase() All uppercase "hello".toUpperCase() "HELLO"
toLowerCase() All lowercase "HELLO".toLowerCase() "hello"
trim() Remove leading/trailing " hi ".trim() "hi"
spaces
equals(s) Compare content (case- "Hi".equals("hi") false
sensitive)
equalsIgnoreCase(s) Compare ignoring case "Hi".equalsIgnoreCase("hi") true
contains(s) Check if substring present "Hello".contains("ell") true
replace(a,b) Replace all a with b "Hello".replace('l','r') "Herro"
split(delim) Split into array by delimiter "a,b,c".split(",") ["a","b","c"]
startsWith(s) Starts with string "Hello".startsWith("He") true
endsWith(s) Ends with string "Hello".endsWith("lo") true
isEmpty() True if length is 0 " ".isEmpty() false
String Examples
Page 8 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
String s = "Information Technology";
// First and last character
char first = [Link](0); // 'I'
char last = [Link]([Link]() - 1); // 'y'
// Extract a word
String word = [Link](12, 22); // "Technology"
// Split by space
String[] words = [Link](" ");
[Link](words[0]); // "Information"
// Check and clean input
String input = " Hello ";
if (![Link]().isEmpty()) {
[Link]([Link]().toUpperCase()); // "HELLO"
}
Page 9 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
7. Math Methods
Method What it does Example Result
[Link](x) Absolute value (removes [Link](-5) 5
negative sign)
[Link](b,e) b to the power of e [Link](2, 8) 256.0
[Link](x) Square root [Link](16) 4.0
[Link](x) Round to nearest integer [Link](3.7) 4
[Link](x) Round UP [Link](3.1) 4.0
[Link](x) Round DOWN [Link](3.9) 3.0
[Link](a,b) Larger of two values [Link](5, 9) 9
[Link](a,b) Smaller of two values [Link](5, 9) 5
[Link]() Random double: 0.0 to <1.0 [Link]() e.g. 0.4712
[Link] The constant π [Link] 3.14159...
Random Numbers in a Range
// Random integer from min to max (inclusive)
int min = 5, max = 15;
int random = (int)([Link]() * (max - min + 1)) + min;
// Example: random number between 500000 and 1500000
int rand = (int)([Link]() * 1000000) + 500000;
// Breakdown:
// [Link]() → 0.0 to 0.9999...
// * 1000000 → 0.0 to 999999.9...
// (int)(...) → 0 to 999999
// + 500000 → 500000 to 1499999
8. Input & Output (I/O)
Console Output
[Link]("Hello"); // prints with new line
[Link]("Hello"); // prints WITHOUT new line
[Link]("Pi = %.2f%n", [Link]); // formatted: Pi = 3.14
// [Link] for building formatted strings
String msg = [Link]("Name: %-15s Age: %3d", name, age);
Console Input — Scanner
import [Link];
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link](); // reads whole line including spaces
[Link]("Enter age: ");
Page 10 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
int age = [Link]();
[Link]("Enter price: ");
double price = [Link]();
// IMPORTANT: after nextInt()/nextDouble(), there is a leftover newline
// Call [Link]() once to consume it before the next nextLine()
int num = [Link]();
[Link](); // consume the leftover newline
String text = [Link](); // now this works correctly
⚠️ Scanner newline trap: After calling nextInt() or nextDouble(), always call [Link]() once before
calling nextLine() again. Otherwise the nextLine() reads the empty newline left over from pressing Enter.
9. File I/O — Reading and Writing Files
File I/O is a Grade 11/12 requirement. Always use try-catch with file operations.
Reading from a File
import [Link].*;
import [Link];
try {
Scanner fileScanner = new Scanner(new File("[Link]"));
while ([Link]()) {
String line = [Link]();
[Link](line);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}
Reading and Splitting Lines (CSV-style)
// Example: each line is "Sipho,85,Pass"
try {
Scanner fs = new Scanner(new File("[Link]"));
while ([Link]()) {
String line = [Link]();
String[] parts = [Link](",");
String name = parts[0];
int mark = [Link](parts[1]);
String grade = parts[2];
[Link](name + " scored " + mark);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("Error: " + [Link]());
}
Page 11 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
Writing to a File
import [Link].*;
// PrintWriter — overwrites the file
try {
PrintWriter pw = new PrintWriter(new File("[Link]"));
[Link]("Line 1");
[Link]("Line 2");
[Link](); // ALWAYS close — data may not save without this
} catch (FileNotFoundException e) {
[Link]("Cannot write: " + [Link]());
}
// FileWriter with append=true — adds to existing file
try {
PrintWriter pw = new PrintWriter(new FileWriter("[Link]", true));
[Link]("New entry");
[Link]();
} catch (IOException e) {
[Link]("IO Error: " + [Link]());
}
⚠️ Always close files: Not closing a PrintWriter can result in data not being written. Call [Link]() or use
try-with-resources.
Page 12 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
10. Exception Handling
Exceptions are runtime errors that crash your program. try-catch prevents the crash and lets you handle the
error gracefully.
Basic try-catch Structure
try {
// Code that might throw an exception
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
} finally {
[Link]("This runs always, whether exception or not");
}
Multiple catch blocks
try {
String input = [Link]();
int num = [Link](input); // NumberFormatException if not a
number
int result = 100 / num; // ArithmeticException if num = 0
[Link]("Result: " + result);
} catch (NumberFormatException e) {
[Link]("Please enter a valid number.");
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
} catch (Exception e) {
[Link]("Unexpected error: " + [Link]());
}
Common Exception Types
Exception Cause
ArithmeticException Division by zero
NumberFormatException [Link]("abc") — not a valid number
ArrayIndexOutOfBoundsException Accessing arr[5] when arr only has 4 elements
NullPointerException Calling a method on a null object reference
FileNotFoundException File does not exist at the given path
IOException General file read/write error
StringIndexOutOfBoundsException charAt(10) on a string with fewer than 11 chars
Page 13 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
11. OOP — Classes and Objects
A class is a blueprint. An object is an instance of that class. OOP is the most heavily weighted topic in the
practical exam.
Full Class Template
public class Student {
// ── FIELDS (private for encapsulation) ──────────────────────────
private String name;
private int age;
private double mark;
private static int studentCount = 0; // class variable — shared by all
// ── CONSTRUCTOR ─────────────────────────────────────────────────
public Student(String name, int age, double mark) {
[Link] = name; // 'this' refers to the current object
[Link] = age;
[Link] = mark;
studentCount++;
}
// ── GETTERS (Accessors) ──────────────────────────────────────────
public String getName() { return name; }
public int getAge() { return age; }
public double getMark() { return mark; }
public static int getStudentCount() { return studentCount; }
// ── SETTERS (Mutators) ───────────────────────────────────────────
public void setName(String name) { [Link] = name; }
public void setAge(int age) {
if (age > 0 && age < 120) // data validation in setter
[Link] = age;
else
[Link]("Invalid age");
}
public void setMark(double mark) { [Link] = mark; }
// ── OWN METHOD ───────────────────────────────────────────────────
public String getGrade() {
if (mark >= 75) return "Distinction";
else if (mark >= 50) return "Pass";
else return "Fail";
}
// ── toString ─────────────────────────────────────────────────────
@Override
public String toString() {
return [Link]("Name: %-20s Age: %3d Mark: %.1f Grade: %s",
name, age, mark, getGrade());
}
}
Page 14 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
Creating and Using Objects
// In [Link] or another class:
Student s1 = new Student("Sipho", 17, 82.5);
Student s2 = new Student("Lerato", 18, 61.0);
// Using getters
[Link]([Link]()); // "Sipho"
[Link]([Link]()); // "Distinction"
// Using setters
[Link](90.0);
// toString is called automatically when printing
[Link](s1); // calls [Link]()
// Array of objects
Student[] students = new Student[30];
students[0] = new Student("James", 17, 55.0);
// Class variable
[Link]([Link]()); // 2
📝 this keyword: [Link] refers to the field. name (without this) refers to the parameter. When they have
the same name, use this to distinguish them.
📝 static vs non-static: static methods/fields belong to the CLASS (shared by all objects). Non-static
belongs to each individual OBJECT. Call static with [Link](), non-static with
[Link]().
Page 15 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
12. Inheritance
Inheritance allows a subclass to inherit fields and methods from a superclass. Use extends keyword. Key
principle: 'is-a' relationship.
Superclass
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
[Link] = name;
[Link] = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public String makeSound() {
return "Some generic sound";
}
@Override
public String toString() {
return "Name: " + name + " Age: " + age;
}
}
Subclass — extends the superclass
public class Dog extends Animal {
private String breed; // additional field only Dog has
public Dog(String name, int age, String breed) {
super(name, age); // MUST call superclass constructor first
[Link] = breed;
}
public String getBreed() { return breed; }
// METHOD OVERRIDING — replacing the superclass version
@Override
public String makeSound() {
return "Woof!";
}
@Override
public String toString() {
return [Link]() + " Breed: " + breed;
// [Link]() calls Animal's toString first
}
Page 16 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
}
Using Inheritance
Dog d = new Dog("Rex", 3, "Labrador");
[Link]([Link]()); // inherited from Animal
[Link]([Link]()); // Dog's own method
[Link]([Link]()); // "Woof!" — overridden version
[Link](d); // calls Dog's toString
// Polymorphism — Animal reference holds a Dog object
Animal a = new Dog("Buddy", 2, "Poodle");
[Link]([Link]()); // "Woof!" — runtime decides which version
What is inherited?
Inherited? Member
✅ Yes public methods
✅ Yes protected methods and fields
✅ Yes public fields (but should be private with getters)
❌ No private fields (must use getters/setters)
❌ No constructors (but can call with super())
❌ No static methods (they belong to the class, not the object)
⚠️ super() must be the first line: If you call super() in a subclass constructor, it must be the very first
statement. Failing to do this causes a compile error.
OOP Concepts Summary
Concept Definition Java Mechanism
Encapsulation Hiding data inside a class, only private fields + public getters/setters
exposing it through methods
Inheritance A subclass acquires fields and class Dog extends Animal
methods from a superclass
Polymorphism One method name, multiple Method overriding (@Override)
implementations
Overloading Same method name, different Multiple method definitions
parameter lists
Overriding Subclass replaces a superclass @Override annotation
method
Abstraction Hiding complex implementation, Methods, classes
showing only what's needed
Page 17 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
13. ArrayList — Dynamic Arrays
Unlike arrays, ArrayLists grow and shrink automatically. They can only store objects (not primitives directly —
use wrapper classes).
Setup and Basic Operations
import [Link];
// Create
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> nums = new ArrayList<>(); // <> shorthand
ArrayList<Student> students = new ArrayList<>();
// Add
[Link]("Sipho");
[Link]("Lerato");
[Link](0, "James"); // insert at index 0
// Access
[Link]([Link](0)); // "James"
[Link]([Link]()); // 3 (use .size() not .length)
// Modify
[Link](1, "Nomsa"); // replace index 1
// Remove
[Link](0); // remove by index
[Link]("Nomsa"); // remove by value
// Check
boolean has = [Link]("Sipho");
boolean empty = [Link]();
// Clear
[Link]();
Looping through an ArrayList
// Enhanced for loop (preferred)
for (String name : names) {
[Link](name);
}
// Standard for loop (when you need the index)
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i).getName());
}
ArrayList of Objects
ArrayList<Student> list = new ArrayList<>();
[Link](new Student("Sipho", 17, 82.5));
Page 18 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
[Link](new Student("Lerato", 18, 61.0));
// Find student with highest mark
Student best = [Link](0);
for (Student s : list) {
if ([Link]() > [Link]()) {
best = s;
}
}
[Link]("Best student: " + best);
Array ArrayList
Size Fixed — set at declaration Dynamic — grows/shrinks automatically
Syntax int[] arr = new int[5] ArrayList<Integer> list = new ArrayList<>()
Access arr[i] [Link](i)
Length [Link] [Link]()
Add element Not possible (size fixed) [Link](value)
Remove element Not possible [Link](index)
Primitives Allowed (int, double etc.) Must use wrappers (Integer, Double)
Page 19 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
14. Algorithms — Sorting
The SAGS requires you to implement sorting from first principles — do NOT use [Link]() or
[Link]() unless asked.
Bubble Sort — compare adjacent pairs, bubble largest to end
public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) { // passes
for (int j = 0; j < n - 1 - i; j++) { // comparisons per pass
if (arr[j] > arr[j + 1]) { // swap if out of order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// After each pass, the largest unsorted element is in its final position
// For descending: change arr[j] > arr[j+1] to arr[j] < arr[j+1]
Selection Sort — find minimum, swap into position
public static void selectionSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// Swap arr[i] with arr[minIdx]
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
}
Sorting an Array of Objects by a field
// Sort students array by mark (ascending) using bubble sort
for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (students[j].getMark() > students[j+1].getMark()) {
Student temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
Page 20 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
15. Algorithms — Searching
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; // return index where found
}
}
return -1; // -1 means not found
}
// Usage:
int idx = linearSearch(scores, 85);
if (idx != -1) [Link]("Found at index " + idx);
else [Link]("Not found");
Binary Search — ONLY works on a SORTED array
public static int binarySearch(int[] arr, int target) {
int low = 0, high = [Link] - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) return mid; // found
else if (arr[mid] < target) low = mid + 1; // search right half
else high = mid - 1; // search left half
}
return -1; // not found
}
Linear Search Binary Search
Requires sorted data No Yes — must sort first
Best case O(1) — first element O(1) — middle element
Worst case O(n) — checks every element O(log n) — halves each time
Use when Unsorted or small data Large sorted data
Page 21 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
16. Common Mistakes — Quick Reference
Mistake Correct Approach
Using == to compare Strings Use .equals() or .equalsIgnoreCase()
Integer division: 7/2 = 3 Cast to double: (double)7/2 or 7.0/2
Forgetting break in switch Every case needs break unless intentional fall-through
Scanner newline not consumed Call [Link]() after nextInt()/nextDouble()
Accessing arr[[Link]] Last index is [Link]-1, not [Link]
Not closing files Always call [Link]() or [Link]()
super() not first in constructor super() must be the very first line in a subclass constructor
Calling static method on object Use [Link](), not [Link]()
Using .length on ArrayList ArrayLists use .size(), arrays use .length
Sorting before binary search Always sort the array before applying binary search
Private field accessed directly in subclass Use the getter method — private fields are not inherited
directly
Forgetting @Override Use @Override when overriding — helps the compiler catch
errors
Not using this in constructor When parameter name = field name, use [Link] = name
Infinite loop — no update Always update the loop variable inside while/do-while loops
Printing object without toString Implement toString() so [Link](obj) shows
useful info
17. Full Program Structure Template
This is the typical structure of a well-written Grade 12 practical exam solution.
[Link] — the driver class
import [Link];
import [Link];
import [Link].*;
public class Main {
static Scanner sc = new Scanner([Link]);
public static void main(String[] args) {
// 1. Load data from file
ArrayList<Student> students = loadStudents("[Link]");
// 2. Display menu
int choice;
do {
[Link]("\n1. Display all");
[Link]("2. Search");
[Link]("3. Sort");
[Link](0 + ". Exit");
[Link]("Choice: ");
choice = [Link]();
[Link]();
Page 22 of 23 | Java Study Notes – Grade 12 IT
JAVA COMPLETE STUDY NOTES – GRADE 12 IT PRACTICAL EXAM Aligned to IEB SAGS
switch (choice) {
case 1: displayAll(students); break;
case 2: search(students); break;
case 3: sortStudents(students); break;
}
} while (choice != 0);
}
public static ArrayList<Student> loadStudents(String filename) {
ArrayList<Student> list = new ArrayList<>();
try {
Scanner fs = new Scanner(new File(filename));
while ([Link]()) {
String line = [Link]();
String[] parts = [Link](",");
String name = parts[0];
int age = [Link](parts[1].trim());
double mark = [Link](parts[2].trim());
[Link](new Student(name, age, mark));
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found.");
}
return list;
}
public static void displayAll(ArrayList<Student> list) {
for (Student s : list) {
[Link](s);
}
}
// Add search, sort methods here...
}
End of Java Study Notes — Good luck with your exam!
Page 23 of 23 | Java Study Notes – Grade 12 IT