0% found this document useful (0 votes)
2 views30 pages

Java Learning Simplified

This document is a beginner's guide to Java programming, covering fundamental concepts such as variables, data types, operators, control structures, classes, and object-oriented programming principles. It explains Java's features, how it works, and provides examples and analogies in Shona to aid understanding. The content is structured into chapters that progressively build knowledge for absolute beginners in Java.

Uploaded by

babongilemoyofx
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

Java Learning Simplified

This document is a beginner's guide to Java programming, covering fundamental concepts such as variables, data types, operators, control structures, classes, and object-oriented programming principles. It explains Java's features, how it works, and provides examples and analogies in Shona to aid understanding. The content is structured into chapters that progressively build knowledge for absolute beginners in Java.

Uploaded by

babongilemoyofx
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA

For Absolute Beginners

Inorereredza seMaize — Pakatanga kusara

HCSE224 / OOP · MSU · Tariro Magadza

CHAPTER TOPIC

1 What is Java? — Chii chinonzi Java?

2 How Java Works — Kushanda kwaJava

3 Variables & Data Types — Nzvimbo dzekuchengetera data

4 Operators — Zvinotarisana nenhamba

5 Control Structures — if, switch, loops

6 Classes & Objects — The Heart of OOP

7 The 4 OOP Pillars — Mapatya 4 eOOP

8 Constructors, this & super

9 Inheritance — Nhaka

10 Overloading vs Overriding

11 Abstract Classes & Interfaces

12 Exception Handling — Kuita Zvakaipa kana Error


13 Built-in Classes (String, Math, Arrays, Scanner)

14 Collections (List, Set, Map)

15 Quick Cheat Sheet


Chapter 1 — What is Java? (Chii chinonzi Java?)
■ Java is a programming language. A programming language is just a way of giving instructions to a
computer. Like how you give instructions to a friend — but in a language the computer understands.
■■ Shona analogy: Funganya kuti computer ndiwo muranda wako. Java ndiyo mutauro
waunodzidza kumuudza kuti: 'Ita izvi.' Kana usina Java, haukwanisi kutaura nemuranda wako.
(Java is instructions for a computer)

Why Java specifically?

Feature What it means Simple version

Platform Independent Write once, run on any computer Like writing a letter — anyone can
read it regardless of their phone brand

Object Oriented Code is organized into 'objects' (like Like how a car is an object that has
real-life things) colour, speed, brand

Simple Easy to learn, similar to English No need to manage memory yourself


like in C

Secure Built-in security features Like a locked safe — harder to hack

Robust Handles errors gracefully Program warns you instead of just


crashing silently

Multithreaded Can do multiple things at once Like cooking rice AND doing dishes at
the same time

■ REMEMBER: Examiners LOVE asking 'State 5 features of Java'. Memorise the table above.
Chapter 2 — How Java Works (Kushanda kwaJava)
■ You write code → the computer reads it. But a computer does NOT understand English. So Java has
a process that converts your code into something the computer can run.
■■ Shona analogy: Fungidzira kuti wakanyora tsamba muChiShona asi umwe munhu anogona
kuireader chete kana yatukulwa ku-English. Java inofamba nenzira imwechete — inoshandura
code yako. (Java needs to translate your code)

The 3 Key Steps

Step What happens Result

1. You write code You type Java code in a file called .java file saved on disk
[Link]

2. Compiler (javac) javac reads your .java file and converts it .class file created (bytecode)
to bytecode

3. JVM runs it The Java Virtual Machine (JVM) reads Output on screen
the .class file and runs it on YOUR
specific computer

■ BYTECODE is the middle step. It is NOT machine language yet. It is portable code that any JVM on
any OS can run. That is the secret to 'Write Once, Run Anywhere'.
■■ Shona analogy: JVM (Java Virtual Machine) ifanana nemunhu anotaura Shona, English,
nePortuguese. Unonyora tsamba imwe chete uye JVM anoiverengera vanhu vose, paWindows,
pa Mac, paLinux. (JVM = the translator that runs everywhere)

First Java Program Ever


Every Java program starts with a class and a main method. The main method is where Java starts
running. Always.

public class Hello { // class name = file name


public static void main(String[] args) { // Java starts HERE
[Link]('Hello World!'); // print to screen
}
}

Part Plain English

public class Hello Create a class (blueprint) called Hello. File MUST be named [Link]

public static void main This is the entry point. Java looks for THIS exact name to start running
String[] args A way to pass in values when starting the program. Don't overthink it
— just always write it

[Link](...) Print something to the screen. println = print line (adds a new line at
the end)
Chapter 3 — Variables & Data Types (Nzvimbo
dzekuchengetera data)
■ A variable is a box in the computer's memory where you store a value. You give the box a name and a
type (what kind of thing fits inside).
■■ Shona analogy: Fungidzira kuti une maturusi akawanda emba yako. Une chipfuva
chekuchengetera hembe, imwe nzvimbo yemari, imwe yemabhuku. Variable ndiyo nzvimbo
yacho — unopea zita kuti uzive zviri mukati. (Variable = chipfuva chekuchengetera zvinhu)

Primitive Data Types (8 types)


These are the basic building blocks. Java has 8 primitive types. The most important ones:

Type Stores Example Shona analogy

int Whole numbers (no decimal) int age = 21; Nhamba dzese senge
makore, vanhu

double Numbers with decimal point double price = 9.99; Mari yemutengesi —
inogona kuva nemasendi

char ONE single character char grade = 'A'; Bhenzi rimwe chete
chikwaro

boolean true or false ONLY boolean pass = true; Mubvunzo wekuti:


'Wakapfuura here?' —
Hongu/Kwete

String Words / sentences (NOT String name = "Tariro"; Mazwi, mazita — zvinosvika
primitive but used as one) zvakawanda

float Decimal numbers (less float tax = 3.5f; Kufanana nedouble asi diki
precise than double)

long Very large whole numbers long pop = 15000000L; Nhamba huru kwazvo —
senge population

byte Tiny numbers -128 to 127 byte x = 100; Hapana kuita 200 — diki
kwazvo

Declaring and Using Variables


int age = 21; // declare AND give a value at once
String name = "Tariro"; // String uses double quotes
char grade = 'A'; // char uses SINGLE quotes — only ONE letter
boolean passed = true; // only true or false
double salary = 1500.50; // decimal number

// Print them
[Link]("Name: " + name); // + joins text together
[Link]("Age: " + age);
[Link]("Passed: " + passed);

■■ char uses SINGLE quotes 'A'. String uses DOUBLE quotes "Hello". Mix them up and your
code will NOT compile.

3 Types of Variables

Type Where declared Who can use it

Local variable Inside a method Only that method

Instance variable Inside a class (outside methods) Any method in the class, via an
object

Static variable Inside class with 'static' keyword All objects share ONE copy
Chapter 4 — Operators (Zvishandiso zvenhamba)
■ Operators are symbols that DO something to values. Plus, minus, multiply, compare — all of that.

Arithmetic Operators

Symbol Meaning Example Result

+ Add 5+3 8

- Subtract 10 - 4 6

* Multiply 3*4 12

/ Divide 10 / 2 5

% Modulus (remainder after 10 % 3 1 (10 / 3 = 3 remainder 1)


division)

■■ Shona analogy: Kana ukagovana mangana 10 kuvanhu 3, mumwe munhu anowana mangana
mangani? Anowana 1. Ndiyo % inoita — inokupa zvasara. (Modulus % = the leftovers)

Comparison Operators (return true or false)

Symbol Meaning Example

== Equal to age == 18 → true if age is 18

!= NOT equal to name != "Bob" → true if name is not Bob

> Greater than score > 50

< Less than price < 100

>= Greater than or equal to age >= 18

<= Less than or equal to marks <= 40

■■ == compares VALUES. Never use == to compare Strings — use .equals() instead! Example:
[Link]("Tariro")

Shortcut Assignment Operators

Shortcut Same as Used when

x++ x=x+1 Adding 1 to a counter in a loop


x-- x=x-1 Counting down

x += 5 x=x+5 Increasing by a specific amount

x -= 5 x=x-5 Decreasing by a specific amount

x *= 2 x=x*2 Doubling a value

x /= 2 x=x/2 Halving a value


Chapter 5 — Control Structures (if, switch, loops)
■ Control structures let your program MAKE DECISIONS and REPEAT actions. Without them, your
program just runs from top to bottom and does the same thing every time. Boring.
■■ Shona analogy: Kana program yako isingakwanisi kusarudza, inofanana nemunhu asinga
fungi — anoita chero chimwe. if/switch zvinoisa pfungwa. Loops zvinoita kuti ashandirire.
(Control structures = pfungwa dzeprogram yako)

if / else if / else
int marks = 65;

if (marks >= 70) {


[Link]('Distinction!');

} else if (marks >= 50) {


[Link]('Pass'); // runs if first if was false AND this is true

} else {
[Link]('Fail'); // runs if ALL above conditions were false
}

■ Java checks conditions TOP to BOTTOM. The FIRST one that is true runs. The rest are SKIPPED. It
does not check them all.

switch statement
■ switch is like if/else but cleaner when you're checking ONE variable against many specific values.
char grade = 'B';

switch (grade) {
case 'A':
[Link]('Excellent!');
break; // IMPORTANT: break stops the switch here
case 'B':
[Link]('Good job');
break;
case 'C':
[Link]('Average');
break;
default: // runs if no case matched — like 'else'
[Link]('Below average');
}

■■ Always write break; at the end of each case. Without it, Java 'falls through' and runs the
NEXT case too. This is a very common bug.
for loop — when you know how many times
// Print 1 to 5
for (int i = 1; i <= 5; i++) {
[Link](i);
}
// for (START ; KEEP-GOING-WHILE ; STEP)
// i=1 : start at 1
// i<=5 : keep going while i is 5 or less
// i++ : after each loop, add 1 to i

while loop — when you DON'T know how many times


int number = 1;

while (number <= 10) { // check condition BEFORE running


[Link](number);
number++; // IMPORTANT: must update or loop runs forever!
}

do-while loop — runs at least ONCE


int number = 1;

do {
[Link](number); // runs first, THEN checks condition
number++;
} while (number <= 5); // note: semicolon at the end!

// KEY DIFFERENCE: Even if number started at 100,


// the body runs ONCE before checking number <= 5

Loop Checks condition Min runs Best for

for Before each run 0 Known count (1 to 10, for each item in
list)

while Before each run 0 Unknown count (keep going while user
hasn't quit)

do-while AFTER each run 1 Menu systems — show menu at least


once before asking to quit
Chapter 6 — Classes & Objects (Mumvuri neChokwadi)
■■ Shona analogy: Fungidzira kuti Class ndiyo marongero (blueprint) emba. Object ndiye imba
chaiyo yakavakwa kubva kumarongero acho. Unogona kuvaka dzimba dzakawanda (objects)
kubva kubluepint imwe (class) chete. (Class = blueprint. Object = the actual thing)

■ A Class is just a TEMPLATE. An Object is a REAL instance created from that template. A class
defines WHAT a thing has (fields) and WHAT it can do (methods).

Creating a Class
public class Car {

// FIELDS — what the car HAS (attributes)


String brand;
String color;
int speed;

// METHOD — what the car CAN DO (behaviour)


public void accelerate() {
speed = speed + 10;
[Link](brand + ' is now going ' + speed + ' km/h');
}

public void displayInfo() {


[Link]('Brand: ' + brand);
[Link]('Colour: ' + color);
}
}

Creating Objects & Using Them


public class TestCar {
public static void main(String[] args) {

// Create an OBJECT from the Car class


Car myCar = new Car(); // 'new' creates a fresh object in memory

// Give the object values


[Link] = "Toyota";
[Link] = "Red";
[Link] = 0;

// Call methods on the object


[Link]();
[Link]();

// Create ANOTHER object from the same class


Car yourCar = new Car();
[Link] = "Honda";
[Link] = "Blue";
[Link] = 0;
[Link]();
}
}

■ myCar and yourCar are TWO separate objects. Changing [Link] does NOT affect
[Link]. They are independent.
Chapter 7 — The 4 OOP Pillars (Mapatya Mana eOOP)
■ These 4 concepts are the FOUNDATION of Object Oriented Programming. Examiners ask about
these in EVERY paper. Learn them cold.

The 4 OOP Pillars — Quick Definitions

1. Encapsulation — Hide your data inside a class. Only let people access it through getters/setters.

2. Inheritance — A child class gets all the fields and methods of its parent class.

3. Polymorphism — One method name, many different behaviours (overloading + overriding).

4. Abstraction — Show only what is needed. Hide the messy internal details.

1. Encapsulation — Lock the fields, use getters/setters


■■ Shona analogy: Bhuku rako rechinyorwa ndere wako. Unorichengetera muhomwe (private).
Kana mumwe munhu achida kuziva zviri mukati, anokubvunza (getter). Kana achida kuchinja,
anofanira kukuudza (setter). Haaendi kunobvunura bhuku rako akananga. (Encapsulation = your
personal diary)
public class Student {

private String name; // private = LOCKED. Can't access directly from outside
private int age;

// GETTER — let others READ the value


public String getName() {
return name;
}

// SETTER — let others CHANGE the value (with control)


public void setName(String name) {
[Link] = name; // '[Link]' = the field. 'name' = the parameter
}

public int getAge() { return age; }

public void setAge(int age) {


if (age > 0) { // you can add VALIDATION in setters
[Link] = age;
}
}
}

2. Inheritance — extends keyword


■■ Shona analogy: Kana baba vachirima munda, mwanakomana anogonawo kuwana munda
uyu (nhaka). Mwanakomana anowana zvose zvababa, uye anogona kuwedzera zvake pachake.
Java inoita izvozvo ne 'extends'. (Nhaka — Inheritance)
// PARENT class
public class Animal {
String name;
public void eat() {
[Link](name + ' is eating');
}
}

// CHILD class — gets everything from Animal


public class Dog extends Animal {
public void bark() {
[Link](name + ' says: Woof!'); // name is INHERITED
}
}

// Test
Dog d = new Dog();
[Link] = "Buddy";
[Link](); // inherited from Animal
[Link](); // Dog's own method

3. Polymorphism — many forms, one name


■■ Shona analogy: Ndiwo mufananidzo: Mwana anogona kutaura ne sekuru vake ne-Shona, ne
shamwari yake ne-English, uye nemwana mudiki ne-baby talk. Zita rimwe 'kutaura' asi nzira
dzakawanda. Java inofanana. (Polymorphism = gwara rimwe, mifananidzo yakawanda)
Polymorphism comes in two forms: Overloading (same class) and Overriding (parent/child). Full details in
Chapter 10.

4. Abstraction — show only what matters


■■ Shona analogy: Unongodirova motokari uchiziva kuti pedari inokumisisa. Hauzi kuziva
maitiro emajecha ari mukati. Iyo ndiyo abstraction — inoficha zvinhu zvakawanda, inoratidza
zvaunoda chete. (Abstraction = drivayi yemotokari)
// Abstract class — can't create an object directly from this
abstract class Shape {
abstract double area(); // abstract method: no body, must be implemented by child

public void display() {


[Link]('Area = ' + area()); // uses child's version
}
}

class Circle extends Shape {


double radius;
Circle(double r) { [Link] = r; }
@Override
public double area() {
return [Link] * radius * radius; // pi r squared
}
}
Chapter 8 — Constructors, this & super
■ A constructor is a special method that runs AUTOMATICALLY when you create a new object. It sets
up the object with starting values. Think of it as the birth certificate of an object.
■■ Shona analogy: Kana mwana aberekwa, anatambira zita, achirekodhwa, achibviswa
mu-hospital. Izvozvo zvose zvinoitika OTOMATIKI. Constructor inofanana — inoita zvinhu
otomatiki paunoita 'new'. (Constructor = mwana achiberekwa)

public class Person {


String name;
int age;

// DEFAULT constructor (no parameters)


public Person() {
name = 'Unknown';
age = 0;
}

// PARAMETERISED constructor (takes values)


public Person(String name, int age) {
[Link] = name; // '[Link]' = the FIELD (box)
[Link] = age; // 'name' alone = the PARAMETER (value passed in)
}

public void show() {


[Link](name + ' is ' + age + ' years old');
}
}

// Usage:
Person p1 = new Person(); // calls default constructor
Person p2 = new Person('Tariro', 21); // calls parameterised constructor
[Link](); // Unknown is 0 years old
[Link](); // Tariro is 21 years old

'this' keyword
■ 'this' refers to the CURRENT object. It is mainly used in constructors when the parameter name and
the field name are the same — to separate them.
public void setName(String name) {
[Link] = name; // [Link] = field. name = parameter
}
// Without 'this', Java gets confused about which 'name' you mean

'super' keyword
■ 'super' is used in a CHILD class to call the PARENT class's constructor or methods.
class Animal {
String name;
Animal(String name) {
[Link] = name;
}
}

class Dog extends Animal {


String breed;

Dog(String name, String breed) {


super(name); // MUST be FIRST line — calls Animal(name)
[Link] = breed; // then set Dog's own field
}
}

■■ super() must ALWAYS be the FIRST line in a child constructor. If you put anything before it,
your code will not compile.
Chapter 9 — Inheritance (Nhaka)
■ Inheritance lets a child class GET all the fields and methods of a parent class. This means you don't
have to rewrite the same code again. The child just adds what's new.

Type Description Example

Single One child inherits from one parent Dog extends Animal

Multilevel Chain: grandparent → parent → child Puppy extends Dog extends Animal

Hierarchical Many children from one parent Cat, Dog, Bird all extend Animal

Multiple One child from multiple parents (NOT Use interfaces instead
allowed in Java with classes, only
interfaces)

// Multilevel inheritance example


class Vehicle {
int speed;
void move() { [Link]('Vehicle moving at ' + speed); }
}

class Car extends Vehicle { // Car inherits from Vehicle


String brand;
void display() { [Link]('Brand: ' + brand); }
}

class ElectricCar extends Car { // ElectricCar inherits from Car (and Vehicle!)
int batteryLevel;
void charge() { [Link]('Charging... ' + batteryLevel + '%'); }
}

// ElectricCar can use: move() (from Vehicle), display() (from Car), charge() (own)
ElectricCar tesla = new ElectricCar();
[Link] = 100;
[Link] = "Tesla";
[Link] = 80;
[Link](); // inherited from Vehicle
[Link](); // inherited from Car
[Link](); // own method
Chapter 10 — Overloading vs Overriding
■ These two look similar but they are TOTALLY different. This is one of the most common exam
questions at MSU.

Feature Overloading Overriding

Where SAME class Parent → Child class

Method name SAME SAME

Parameters DIFFERENT (must differ) SAME (identical signature)

Return type Can differ Must be same (or subtype)

When decided Compile time Run time

Keyword Nothing special @Override (recommended)

Shona Nzira nhatu dzekunarirwa doro rimwe Mwana anochinja nzira yababa — baba
— Beer, Wine, Juice vanorimba, mwana anomira nzira yake

Overloading Example
public class Calculator {

// Version 1: two ints


public int add(int a, int b) {
return a + b;
}

// Version 2: three ints (SAME name, different number of params)


public int add(int a, int b, int c) {
return a + b + c;
}

// Version 3: two doubles (SAME name, different param TYPES)


public double add(double a, double b) {
return a + b;
}
}

Calculator c = new Calculator();


[Link](2, 3); // Java picks version 1
[Link](1, 2, 3); // Java picks version 2
[Link](1.5, 2.5); // Java picks version 3

Overriding Example
class Animal {
public void speak() {
[Link]('Some animal sound...');
}
}

class Dog extends Animal {


@Override // optional but GOOD PRACTICE
public void speak() { // SAME name, SAME params — replaces parent version
[Link]('Woof!');
}
}

class Cat extends Animal {


@Override
public void speak() {
[Link]('Meow!');
}
}

Animal a = new Dog(); // Animal reference, Dog object


[Link](); // prints 'Woof!' — uses Dog's version at runtime
Chapter 11 — Abstract Classes & Interfaces

Feature Abstract Class Interface

Can have normal methods? YES Only default/static methods

Can have fields? YES Only public static final constants

Constructor? YES (but can't be used directly) NO

A class can... extend only ONE abstract class implement MANY interfaces

Keyword abstract class interface / implements

Use when Classes share some common Unrelated classes share a behaviour
code

// ---- ABSTRACT CLASS ----


abstract class Shape {
String color; // normal field

abstract double area(); // abstract = no body. Child MUST implement.

public void displayColor() { // normal method — child inherits this


[Link]('Color: ' + color);
}
}

class Circle extends Shape {


double radius;
Circle(double r) { [Link] = r; [Link] = "Red"; }

@Override
public double area() { return [Link] * radius * radius; }
}

// Shape s = new Shape(); // ERROR! Can't create abstract class object


Shape s = new Circle(5); // OK — Circle is concrete
[Link]([Link]());
[Link]();

// ---- INTERFACE ----


interface Flyable {
void fly(); // all methods are public abstract by default
}

interface Swimmable {
void swim();
}

// A class can implement MULTIPLE interfaces (unlike extends)


class Duck extends Animal implements Flyable, Swimmable {
public void fly() { [Link]('Duck flying'); }
public void swim() { [Link]('Duck swimming'); }
}
Chapter 12 — Exception Handling (Kuisa Maitiro
Pazvikanganiso)
■ An exception is an ERROR that happens while the program is running. Without handling, the program
CRASHES. Exception handling lets your program fail gracefully and show a helpful message instead.
■■ Shona analogy: Kana uchaenda rwendo, unotora inushurenzi yemotokari. Kana zvikanganiso
zvikaitika, haupotsi — inushurenzi inokusimbisa. try/catch inofanana — inosunga program yako
kana zvaipa. (Exception handling = accident insurance)

public class ExceptionDemo {


public static void main(String[] args) {

try {
// Put risky code here
int result = 10 / 0; // dividing by zero = crash!
[Link](result);

} catch (ArithmeticException e) {
// Runs ONLY if an error occurs in try
[Link]('Error: ' + [Link]());

} finally {
// Runs ALWAYS — whether there was an error or not
[Link]('This always runs.');
}
}
}

Block When it runs Required?

try { } Always — wrap risky code here YES

catch (E e) Only if an exception occurs in try YES (at least one)

finally { } ALWAYS — runs whether exception or not. Good for NO (optional)


cleanup.

Common Exception Types

Exception Cause

ArithmeticException Dividing by zero (10 / 0)

NullPointerException Using an object that is null (not created yet)

ArrayIndexOutOfBounds Accessing array[5] when array only has 3 items

NumberFormatException Trying to convert "abc" to an integer


ClassCastException Casting an object to the wrong type
Chapter 13 — Built-in Classes (String, Math, Arrays,
Scanner)

String Methods
■ Strings are objects in Java. They have built-in methods you can call with a dot.
String s = "Hello World";

[Link]() // 11 — number of characters


[Link]() // "HELLO WORLD"
[Link]() // "hello world"
[Link](0) // 'H' — character at position 0
[Link](6) // "World" — from index 6 to end
[Link](0, 5) // "Hello" — from 0 to 5 (not including 5)
[Link]("World") // true — does it contain this?
[Link]("Hello", "Hi") // "Hi World"
[Link]() // removes spaces from BOTH ends
[Link]("Hello World") // true — compare strings (NOT ==)
[Link](" ") // ["Hello", "World"] — split into array

Math Class Methods


[Link](-5) // 5 — absolute value (removes minus sign)
[Link](2, 3) // 8.0 — 2 to the power of 3
[Link](16) // 4.0 — square root
[Link](10, 20) // 20 — the larger of two numbers
[Link](10, 20) // 10 — the smaller
[Link](4.6) // 5 — rounds to nearest integer
[Link](4.9) // 4.0 — always rounds DOWN
[Link](4.1) // 5.0 — always rounds UP
[Link] // 3.14159... — the constant pi
[Link]() // random number between 0.0 and 1.0

Scanner — Reading User Input


import [Link]; // MUST import at top of file

Scanner sc = new Scanner([Link]); // create scanner object

[Link]("Enter your name: ");


String name = [Link](); // read a full line of text

[Link]("Enter your age: ");


int age = [Link](); // read a whole number

[Link]("Enter your salary: ");


double salary = [Link](); // read a decimal number
[Link]("Enter a letter: ");
char letter = [Link]().charAt(0); // read one character

[Link](); // good practice to close scanner when done

Arrays
// Declare and create an array of 5 integers
int[] numbers = {10, 5, 3, 8, 1};

// Access by index (starts at 0!)


[Link](numbers[0]); // 10 (first element)
[Link](numbers[4]); // 1 (last element, index = length-1)

// Array length
[Link]([Link]); // 5

// Loop through array


for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}

// Sort ascending
import [Link];
[Link](numbers); // {1, 3, 5, 8, 10}

// Sort descending (needs Integer[] not int[])


Integer[] nums = {10, 5, 3, 8, 1};
[Link](nums, [Link]());
Chapter 14 — Collections (List, Set, Map)
■ Arrays are fixed size — you must decide the size upfront. Collections are flexible — they grow and
shrink automatically.

Collection Allows duplicates? Ordered? Use when

ArrayList (List) YES YES You want a flexible, ordered list

HashSet (Set) NO NO You want unique values only

HashMap (Map) Keys: NO NO You want key-value pairs (like a


dictionary)

import [Link];
import [Link];

// ---- ArrayList ----


ArrayList<String> names = new ArrayList<>();
[Link]("Tariro");
[Link]("Nyasha");
[Link]("Tariro"); // duplicates allowed
[Link]([Link]()); // 3
[Link]([Link](0)); // Tariro
[Link]("Nyasha");
for (String n : names) { // enhanced for loop
[Link](n);
}

// ---- HashMap ----


HashMap<String, Integer> scores = new HashMap<>();
[Link]("Tariro", 85);
[Link]("Nyasha", 90);
[Link]([Link]("Tariro")); // 85
[Link]([Link]("Nyasha")); // true
for (String key : [Link]()) {
[Link](key + " -> " + [Link](key));
}
Chapter 15 — CHEAT SHEET (Zvekurangarira Zose)

Access Modifiers — Who can see what?

Modifier Same class Child class Same package Everywhere

private ■ ■ ■ ■

(default) ■ ■ ■ ■

protected ■ ■ ■ ■

public ■ ■ ■ ■

Keywords Quick Reference

Keyword What it does

class Defines a class (blueprint)

new Creates an object from a class

extends Inheritance — child gets parent's stuff

implements A class promises to fulfil an interface

abstract Class or method with no complete body — must be implemented

interface A contract of methods a class must implement

this Refers to the current object

super Refers to the parent class

static Belongs to the class, not individual objects (shared by all)

final Can't be changed. Final variable = constant. Final method = can't override. Final
class = can't extend.

void Method returns nothing

return Send a value back from a method

try/catch Handle exceptions (errors)

throws Declare that a method might throw an exception

@Override Annotation showing you are replacing a parent method


The Standard Class Structure Template
■ Every time you are asked to 'write a class', use this structure:
public class ClassName {

// 1. Fields (attributes) — private


private DataType fieldName;

// 2. Constructor
public ClassName(DataType fieldName) {
[Link] = fieldName;
}

// 3. Getters
public DataType getFieldName() {
return fieldName;
}

// 4. Setters
public void setFieldName(DataType fieldName) {
[Link] = fieldName;
}

// 5. Other methods
public void doSomething() {
// logic here
}
}

Java inoronderera semaize — Ungadzidza uchiona zvinomera zuva nezuva. ■


Java grows like maize — learn it daily and you will see results.
Good luck Tariro! — Tigere A's exam won't know what hit it. ■

You might also like